12 people like it.

Split A Seq Into Chunks

This function splits a sequence into lists of length n until there is less than n elements then those are returned.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
module Seq =

    /// Returns a sequence that yields chunks of length n.
    /// Each chunk is returned as a list.
    let toChunks length (source: seq<'T>) =
        use ie = source.GetEnumerator()
        let sourceIsEmpty = ref false
        let rec loop () =
            seq {
                if ie.MoveNext () then
                    yield [
                            yield ie.Current
                            for x in 2 .. length do
                                if ie.MoveNext() then
                                    yield ie.Current
                                else
                                    sourceIsEmpty := true
                    ]
                    match !sourceIsEmpty with
                    | false -> yield! loop ()
                    | true  -> ()
            }
        loop ()

// Demo
[1 .. 20]
|> Seq.toChunks 3
|> Seq.toArray

// Output
// [|[1; 2; 3]; [4; 5; 6]; [7; 8; 9]; [10; 11; 12]; [13; 14; 15]; [16; 17; 18];
// [19; 20]|]
module Seq

from Microsoft.FSharp.Collections
val toChunks : length:int -> source:seq<'T> -> seq<'T list>

Full name: Script.Seq.toChunks


 Returns a sequence that yields chunks of length n.
 Each chunk is returned as a list.
val length : int
val source : seq<'T>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val ie : System.Collections.Generic.IEnumerator<'T>
System.Collections.Generic.IEnumerable.GetEnumerator() : System.Collections.Generic.IEnumerator<'T>
val sourceIsEmpty : bool ref
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
val loop : (unit -> seq<'T list>)
System.Collections.IEnumerator.MoveNext() : bool
property System.Collections.Generic.IEnumerator.Current: 'T
val x : int
Multiple items
module Seq

from Script

--------------------
module Seq

from Microsoft.FSharp.Collections
val toArray : source:seq<'T> -> 'T []

Full name: Microsoft.FSharp.Collections.Seq.toArray
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/es
Posted:11 years ago
Author:Taha Hachana
Tags: seq , list