I would like to group a very large sequence lazily using code like the following:
// native F# version
let groups =
Seq.initInfinite id
|> Seq.groupBy (fun i -> i % 10)
for (i, group) in groups |> Seq.take 5 do
printfn "%A: %A" i (group |> Seq.take 5)
Expected output is:
1: seq [1; 11; 21; 31; ...]
2: seq [2; 12; 22; 32; ...]
3: seq [3; 13; 23; 33; ...]
4: seq [4; 14; 24; 34; ...]
5: seq [5; 15; 25; 35; ...]
However, in practice, this program loops infinitely, printing nothing. Is it possible to accomplish this in F#?
I'd be willing to use Linq instead of native functions, but both GroupBy and ToLookup produce the same behavior (even though Linq's GroupBy is supposed to be lazy):
// Linq version
let groups =
Enumerable.GroupBy(
Seq.initInfinite id,
(fun i -> i % 10))
for group in groups |> Seq.take 5 do
printfn "%A" (group |> Seq.take 5)
Perhaps I'm doing something unintentionally that causes eager evaluation?