HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Console input prompt loop in F#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
inputconsoleloopprompt

Problem

I'm learning F#, starting with baby steps. Is there a way to write this code in a more succint way, while keeping the same semantics? Maybe by using a Seq or something like that?

let rec repeatingPrompt predicate (message:string) =
    Console.WriteLine(message)
    let value = Console.ReadLine()
    if predicate value then
        value
    else
        repeatingPrompt predicate message

Solution

You can use Seq.initInfinite and Seq.find to do this, though I'm not sure it's actually better:

let repeatingPrompt predicate (message:string) =
    let prompt _ =
        Console.WriteLine(message)
        Console.ReadLine()

    Seq.initInfinite prompt |> Seq.find predicate

Code Snippets

let repeatingPrompt predicate (message:string) =
    let prompt _ =
        Console.WriteLine(message)
        Console.ReadLine()

    Seq.initInfinite prompt |> Seq.find predicate

Context

StackExchange Code Review Q#125574, answer score: 5

Revisions (0)

No revisions yet.