Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Split a F# sequence (Seq) into chunks
// Author: Nathan B. Evans
// Twitter: @nbevans
// Blog: https://nbevans.wordpress.com/2014/03/13/really-simple-way-to-split-a-f-sequence-into-chunks-partitions/
// License: MIT
/// Returns a sequence that yields chunks of length n.
/// Each chunk is returned as an array.
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
}
// Ridiculously imperative, but it works and is performant; won't seek the sequence more than once.
// If you're using in a forward-only manner and won't be holding references to the returned chunks
// then you can get rid of the Array.copy to gain some extra perf and reduce GC.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment