Skip to content

Instantly share code, notes, and snippets.

@nbevans
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nbevans/9429542 to your computer and use it in GitHub Desktop.
Save nbevans/9429542 to your computer and use it in GitHub Desktop.
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