我想编写一个函数来将 Console.ReadLine() 抽象为字符串 seq
当 line = null 时,seq 应该中断
ConsoleLines(): unit -> string seq
像这样使用:
for line in ConsoleLines() do
DoSomething line
这个函数怎么写?
谢谢
Seq.initInfinite (fun _ -> Console.ReadLine())
它不是很漂亮,但它按预期工作:
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
}
(请注意,您必须使用 ref/!/:= 在序列表达式中执行可变状态。)
let consoleLines = Seq.takeWhile ((<>) "") (seq { while (true) do yield System.Console.ReadLine() })
稍微不一样:
let readLines (sr:TextReader) =
Seq.initInfinite (fun _ -> sr.ReadLine())
|> Seq.takeWhile (fun x -> x <> null)
let consoleLines() =
readLines Console.In