在C#中,我会这样写:
A
这将提示用户重复输入等式,直到他们输入可以解析的等式。我怎么在F#中做到这一点?
答案 0 :(得分:4)
你可以写一个递归函数:
let rec readInput () =
Console.Write("Enter an equation: ")
let input = Console.ReadLine()
match Infix.TryParse(input) with
| Some(e) -> e
| None -> readInput()
答案 1 :(得分:0)
可能会有点过头,但我曾写过以下内容:
let inputParseLoop msg parser =
let isNull x = Core.obj.ReferenceEquals (x, null)
Seq.initInfinite (fun _ ->
printf "%s " msg
try Some (stdin.ReadLine ()) with _ -> None)
|> Seq.takeWhile Option.isSome
|> Seq.map Option.get
|> Seq.takeWhile (fun s -> not (isNull s))
|> Seq.map parser
|> Seq.skipWhile Option.isNone
|> Seq.head
|> Option.get
对于您的用例,请将其命名为:
inputParseLoop "Enter an equation: " Infix.TryParse