Welcome to F #!
Here is the work program; explanation below.
open System let main() = let answer = (new Random()).Next(1, 100) printfn "Guess the number between 1 and 100" let rec dummyWhileTrue(tries) = let v = Console.ReadLine() if v = "q" then printfn "you have quit" 0 else printfn "blah" let mutable n = 0 let b = Int32.TryParse(v, &n) if b = false then printfn "This is not a number" dummyWhileTrue(tries) elif n = answer then printfn "Correct! You win!" tries elif n < answer then printfn "Guess higher" dummyWhileTrue(tries+1) else // n>answer printfn "Guess lower" dummyWhileTrue(tries+1) let tries = dummyWhileTrue(1) printfn "You guess %d times" tries printfn "Press enter to exit" Console.ReadLine() |> ignore main()
A few things...
If you call methods with multiple arguments (e.g. Random.Next ), use parens around args ( .Next(1,100) ).
You seem to be working on a recursive function ( dummyWhileTrue ), and not in a while loop; the while loop will work too, but I saved it. Note that there is no break or continue in F #, so you should be a little structured with the contents of the if inside.
I changed your Console.WriteLine to printfn to show how to call it with an argument.
I showed a way to call TryParse , which is more like C #. First declare your variable (make it mutable, since TryParse will write to this place), and then use &n as an argument (in this context &n is like ref n or out n in C #), Also in F # you can do this:
let b, n = Int32.TryParse(v)
where F # allows you to omit the trailing out parameters and instead returns their value at the end of the tuple; it's just syntactic convenience.
Console.ReadLine returns a string that you do not need at the end of the program, so pass it to the ignore function to discard the value (and get rid of the warning about an unused string value).
Brian
source share