Most idiomatic way to write batchesOf size seq in F#

前端 未结 10 541
迷失自我
迷失自我 2020-12-16 18:42

I\'m trying to learn F# by rewriting some C# algorithms I have into idiomatic F#.

One of the first functions I\'m trying to rewrite is a batchesOf where:

         


        
10条回答
  •  我在风中等你
    2020-12-16 18:57

    I found this to be a quite terse solution:

    let partition n (stream:seq<_>) = seq {
        let enum = stream.GetEnumerator()
    
        let rec collect n partition =
            if n = 1 || not (enum.MoveNext()) then
                partition
            else
                collect (n-1) (partition @ [enum.Current])
    
        while enum.MoveNext() do
            yield collect n [enum.Current]
    }
    

    It works on a sequence and produces a sequence. The output sequence consists of lists of n elements from the input sequence.

提交回复
热议问题