2

How should one implement a chunking (or partitioning) function for F# sequences? I'm looking for a function with this signature...

val toChunks : n:int -> sequence:seq<'T> -> seq<seq<'T>>

...which returns the items of the original sequence in groups of n items. The input sequence may be unending.

Simple Example

[1; 2; 3; 4; 5; 6; 7; 8; 9]
|> toChunks 4
|> Seq.iter (printfn "%A")

seq [1; 2; 3; 4]
seq [5; 6; 7; 8]
seq [9]
Wallace Kelly
  • 15,565
  • 8
  • 50
  • 71

1 Answers1

1

Nathan Evans suggested this solution:

/// Returns a sequence that yields chunks of length n.
let toChunks n (s:seq<'t>) = seq {
    let pos = ref 0
    let buffer = Array.zeroCreate<'t> n

    for x in s do
        buffer.[!pos] <- x
        if !pos = n - 1 then
            yield buffer |> Array.copy
            pos := 0
        else
            incr pos

    if !pos > 0 then
        yield Array.sub buffer 0 !pos
}

It seems like the best approach to me, but I'd be interested in other solutions.

Wallace Kelly
  • 15,565
  • 8
  • 50
  • 71