Last active
August 29, 2015 13:57
-
-
Save nbevans/9429542 to your computer and use it in GitHub Desktop.
Split a F# sequence (Seq) into chunks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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