Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# return from loop

Tags:

f#

I have the following piece of C++ code that I am trying to implement in F#. I get an error message with F# segment (the line between the if statement). As I understand it, the statement "i" applies not to the function but to the "for" loop?

C++ code

int move( Board b )
{
    for( int i = 0; i < b.size(); ++i )
        if( b(i) != "*" )
           return i;
    return -1;
}

F# code

let move (board:array<string>) :int =
    for i = 0 to (board.Length-1) do
        if( Array.item(i) board <> "*" ) then
            i
    done
    -1
like image 735
minime Avatar asked Dec 04 '25 14:12

minime


1 Answers

You can't break a loop in F#, but don't worry, when you're used to F# you won't need to, it's actually easier:

let move (board:array<string>) :int =
    match Array.tryFindIndex (fun e -> e <> "*") board with
    | Some n -> n
    | None   -> -1
like image 157
Gus Avatar answered Dec 08 '25 22:12

Gus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!