将项目的块(或分区)seq分成N个项目的序列

时间:2014-03-20 21:41:39

标签: f#

如何为F#序列实现分块(或分区)功能?我正在寻找具有此签名的功能......

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

...以n个项目组的形式返回原始序列的项目。输入序列可能是无休止的。

简单示例

[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]

1 个答案:

答案 0 :(得分:1)

Nathan Evans建议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
}

这对我来说似乎是最好的方法,但我对其他解决方案感兴趣。