Seq head and tail

Is there a single layer method to implement nextLine?

let s = ref seqOfLines
let nextLine() =
  let hd = Seq.head !s
  s := Seq.skip 1 !s
  hd

seqOfLines considered infinite

+3
source share
3 answers

One way to do this is to use a basic one IEnumerator<String>. It's not exactly one-line, but it seems to be a little cleaner than yours. (Does not rely on mutable, uses .NET idioms correctly.)

Essentially, you get the IEnumerator <'> interface from the sequence, and then just go to the MoveNext call. This will work perfectly in endless sequence.

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

val getNextFunc : seq<'a> -> (unit -> 'a)

To use, just pass the getNextFuncsequence and it will return your next nextLine function.

> 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"
+4
source

, , , - .

, current state value * next state. . seq LazyList ( F # PowerPack ), :

> open LazyList
let seqOfLines = Seq.initInfinite (fun i -> i) |> LazyList.ofSeq
let nextLine = function Cons(x, xs) -> x, xs | Nil -> failwith "Empty list";;

val seqOfLines : LazyList<int>
val nextLine : LazyList<'a> -> 'a * LazyList<'a>

> nextLine seqOfLines;;
val it : int * LazyList<int> = (0, seq [1; 2; 3; 4; ...])
> nextLine (snd it);;
val it : int * LazyList<int> = (1, seq [2; 3; 4; 5; ...])
> nextLine (snd it);;
val it : int * LazyList<int> = (2, seq [3; 4; 5; 6; ...])
> nextLine (snd it);;
val it : int * LazyList<int> = (3, seq [4; 5; 6; 7; ...])
+2

FSharpx.Collections contains some useful / efficient features like Seq.tail, Seq.Head and Seq.UnCons, which can be useful if you want to decompose Seq into head and tail.

0
source

Source: https://habr.com/ru/post/1784427/


All Articles