F#如何将Console.ReadLine()抽象为字符串seq

时间:2009-02-03 03:04:29

标签: f# console stream sequences

我想编写一个函数来将Console.ReadLine()抽象为字符串seq

当line = null

时,seq应该会中断
ConsoleLines(): unit -> string seq

要像这样使用:

for line in ConsoleLines() do
    DoSomething line

你怎么写这个功能?

由于

5 个答案:

答案 0 :(得分:5)

它不是太漂亮,但它按预期工作:

let rec ConsoleLines() =
    seq {
        match Console.ReadLine() with
        | "" -> yield! Seq.empty
        | x -> yield x; yield! ConsoleLines()
    }

答案 1 :(得分:4)

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
    }

(注意,必须使用ref /!/:=在序列表达式中执行可变状态。)

答案 2 :(得分:4)

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

答案 3 :(得分:2)

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

答案 4 :(得分:2)

略有不同:

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

let consoleLines() =
    readLines Console.In