How can I use a user inputted value in my Function in F#

前端 未结 3 1899
梦如初夏
梦如初夏 2020-12-06 21:48

So I\'m trying to make a simple factorial function in F# that uses a value inputted from the user (using the console, I don\'t know if that makes any difference) but I can\'

3条回答
  •  感动是毒
    2020-12-06 22:31

    Since both:

    somevalue |> int
    

    and

    System.Int32.Parse somevalue
    

    Throw an exception on invalid input is it not better to prevent your app from blowing up at runtime?

    Since I could not find any function that returns int option I wrote one:

    let asInt32 numberString =
      let (success,num)  = 
        System.Int32.TryParse(numberString)
      if success then
        Some num
      else
        None
    asInt32 "22"
    

    (using TryParse as Gustavo suggested)

提交回复
热议问题