简体   繁体   中英

C# To F# loops to return a value

How to Write this code in 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

While you can rewrite C# code to F# line-by-line, you will not really get much of the F# elegance in that way. 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:

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. 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.

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.

If you insist on keeping your code 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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