Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# how to abstract Console.ReadLine() as string seq

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

like image 319
Luca Martinetti Avatar asked Dec 02 '22 08:12

Luca Martinetti


2 Answers

Seq.initInfinite (fun _ -> Console.ReadLine())
like image 62
thr Avatar answered Dec 04 '22 00:12

thr


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()
    }
like image 33
Juliet Avatar answered Dec 04 '22 01:12

Juliet