简体   繁体   English

C#至F#循环返回一个值

[英]C# To F# loops to return a value

How to Write this code in f# 如何在f#中编写此代码

 int IAI.AIMove()
    {
        for (int i = 0; i <= 8; i++)
            if (cBoard.getPlayer(i) == 0)
                return i;
        return 0;
    }

This is what i have 这就是我所拥有的

member this.AIMove()=
      let result =  int in
        for i in 1 .. 8 do
            if cboard.getPlayer(i)=0 then
               result := Some i

[error] This expression was expected to have type int but here has type unit [错误]该表达式应具有int类型,但此处具有type单元

While you can rewrite C# code to F# line-by-line, you will not really get much of the F# elegance in that way. 虽然您可以逐行将C#代码重写为F#,但实际上并不会以这种方式获得F#的优雅。 I'd recommend playing with some really simple problems first (like working with lists) and then thinking about how you could design your project to be a bit more functional. 我建议您先解决一些非常简单的问题(例如使用列表),然后再考虑如何设计项目以使其更具功能性。

To answer your question, you can use List.tryFind instead of loop and mutation: 要回答您的问题,可以使用List.tryFind而不是循环和突变:

let idx = [ 0 .. 8 ] |> List.tryFind (fun i -> cBoard.getPlayer(i) = 0)

This generates a list with numbers from 0 to 1 and then returns first number such that the given predicate returns true. 这将生成一个具有从0到1的数字的列表,然后返回第一个数字,以使给定谓词返回true。 This behaves a bit differently than your code - it returns option<int> which is either None if a value was not found or Some(i) when the value was found. 这与代码的行为有所不同-它返回option<int> ,如果找不到值,则返回None找到值时,返回Some(i)

It is probably a good idea to use options and pattern matching, but you could use defaultArg idx 0 to return 0 if the value was not found. 使用选项和模式匹配可能是一个好主意,但是如果找不到该值,则可以使用defaultArg idx 0返回0。

If you insist on keeping your code C#'ish: 如果您坚持保留代码C#'ish:

member this.AIMove () : int option =
  let result = ref None
  for i in 1 .. 8 do
    if cboard.getPlayer(i)=0 then
      result := Some i
  match !result with
  | Some i -> i
  | None -> 0
type Board =
    member x.getPlayer (i: int) = 0 // Just a stub to allow typechecking

let move (cBoard: Board) =
    let isZero x = x = 0
    let found = seq { 0 .. 8 } |> Seq.tryFind (cBoard.getPlayer >> isZero)
    defaultArg found 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM