Search code examples
arraysf#sequencechunking

F# array_chunk for Sequence


I'm having some trouble making a sequence. Basically I need to chop a sequence into a sequence of arrays. Seq.windowed almost does it but I don't want duplicate elements.

I can get what I want by reading everything into an array first but I'd rather use a sequence.

let array_chunk s (a:int[]) =
    Array.init (a.Length / s) (fun i -> Array.sub a (i * s) s)

someSequence |> Seq.to_array |> array_chunk 5

Solution

  • Here's a nice imperative one that'll work with seq and generate arrays of any size. The last one will be smaller if the sequence isn't even by n.

    let chunk n xs = seq {
        let i = ref 0
        let arr = ref <| Array.create n (Unchecked.defaultof<'a>)
        for x in xs do
            if !i = n then 
                yield !arr
                arr := Array.create n (Unchecked.defaultof<'a>)
                i := 0 
            (!arr).[!i] <- x
            i := !i + 1
        if !i <> 0 then
            yield (!arr).[0..!i-1] }