Question

I want to write a function to abstract Console.ReadLine() into a string seq

the seq should break when line = null

ConsoleLines(): unit -> string seq

To be used like this:

for line in ConsoleLines() do
    DoSomething line

How do you write this function?

Thanks

Was it helpful?

Solution

Seq.initInfinite (fun _ -> Console.ReadLine())

OTHER TIPS

Its not overly pretty, but it works as expected:

let rec ConsoleLines() =
    seq {
        match Console.ReadLine() with
        | "" -> yield! Seq.empty
        | x -> yield x; yield! ConsoleLines()
    }
let ConsoleLines =
    seq {
        let finished = ref false
        while not !finished do
            let s = System.Console.ReadLine()
            if s <> null then
                yield s
            else
                finished := true
    }

(Note that you must use ref/!/:= to do mutable state inside a sequence expression.)

let consoleLines = Seq.takeWhile ((<>) "") (seq { while (true) do yield System.Console.ReadLine() })

Slightly different:

let readLines (sr:TextReader) =
    Seq.initInfinite (fun _ -> sr.ReadLine())
    |> Seq.takeWhile (fun x -> x <> null)

let consoleLines() =
    readLines Console.In
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top