views:

776

answers:

5

Hi,

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

+4  A: 

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()
    }
Juliet
+3  A: 
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.)

Brian
+1  A: 
let consoleLines = Seq.takeWhile ((<>) "") (seq { while (true) do yield System.Console.ReadLine() })
Simon Buchan
+1  A: 

Slightly different:

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

let consoleLines() =
    readLines Console.In
Nathan Howell
+1  A: 
Seq.initInfinite (fun _ -> Console.ReadLine())
thr