I'm learning f# and doing a function which asks for the user to input a number. The function will then display the users input and if it's a positive or negative number. However, when I try running the program it errors and states that the input is a string instead of an int. I don't know a way to convert the function output into a string.
open System
let sign num =
if num > 0 then "positive"
elif num < 0 then "negative"
else "zero"
let main() =
Console.Write("please enter a number:")
let input = Console.ReadLine()
Console.Write("The number {0}", sign 1)
System.Console.ReadKey() |> ignore
main()
Use (int)input
int input
. Under the covers this parses the input and returns an int or throws a System.FormatException.
Another option is to use Int32's TryParse method and return the both the result and success indicator as a tuple. You can also deconstruct the tuple in the same line :
let (ok,number)= System.Int32.TryParse input
let message=if ok then
sprintf "The number %i" number
else
sprintf "%s is not a number" input
Console.WriteLine message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With