简体   繁体   中英

How do I write an input loop in F#?

In C#, I would write this:

string input;
do
{
    Console.Write("Enter an equation: ");
    input = Console.ReadLine();
} while (FSharpOption<Expression>.get_IsNone(Infix.TryParse(input)));

This would prompt the user to enter an equation repeatedly until they enter one that can be parsed. How would I do this in F#?

You could write a recursive function:

let rec readInput () =
    Console.Write("Enter an equation: ")
    let input = Console.ReadLine()
    match Infix.TryParse(input) with
    | Some(e) -> e
    | None -> readInput()

Might be a bit over the top but I once wrote the following:

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

For your use case, call it like this:

inputParseLoop "Enter an equation: " Infix.TryParse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM