Seq 头和尾

Min*_*ang 3 f#

有没有一种简单的方法来实施nextLine

let s = ref seqOfLines
let nextLine() =
  let hd = Seq.head !s
  s := Seq.skip 1 !s
  hd
Run Code Online (Sandbox Code Playgroud)

seqOfLines假设为无限

Chr*_*ith 5

实现此目的的一种方法是利用底层IEnumerator<String>. 它不完全是一句简单的话,但它似乎比您的实现更干净一些。(不依赖可变,正确使用 .NET 习惯用法。)

本质上,您从序列中获取IEnumerator<'a>接口,然后循环调用 MoveNext。这对于无限序列来说效果很好。

> let getNextFunc (seqOfLines : seq<'a>) =               
-     let linesIE : IEnumerator<'a> = seqOfLines.GetEnumerator()
-     (fun () -> ignore (linesIE.MoveNext()); linesIE.Current);;

val getNextFunc : seq<'a> -> (unit -> 'a)
Run Code Online (Sandbox Code Playgroud)

使用时,只需传递getNextFunc一个序列,它将返回您的 nextLine 函数。

> let sequenceOfStrings = seq { for i = 0 to 10000 do yield i.ToString() };;

val sequenceOfStrings : seq<string>

> let nextLine = getNextFunc sequenceOfStrings;;  

val nextLine : (unit -> string)

> nextLine();;
val it : string = "0"
> nextLine();;
val it : string = "1"
> nextLine();;
val it : string = "2"
> nextLine();;
val it : string = "3"
Run Code Online (Sandbox Code Playgroud)