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: 
module Seq =

    /// Returns a sequence that yields chunks of length n.
    /// Each chunk is returned as a list.
    let split length (xs: seq<'T>) =
        let rec loop xs =
            [
                yield Seq.truncate length xs |> Seq.toList
                match Seq.length xs <= length with
                | false -> yield! loop (Seq.skip length xs)
                | true -> ()
            ]
        loop xs

// Demo
[1 .. 20]
|> Seq.split 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 split : length:int -> xs:seq<'T> -> 'T list list

Full name: Script.Seq.split


 Returns a sequence that yields chunks of length n.
 Each chunk is returned as a list.
val length : int
val xs : 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 loop : (seq<'a> -> 'a list list)
val xs : seq<'a>
val truncate : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.truncate
val toList : source:seq<'T> -> 'T list

Full name: Microsoft.FSharp.Collections.Seq.toList
val length : source:seq<'T> -> int

Full name: Microsoft.FSharp.Collections.Seq.length
val skip : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.skip
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

More information

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