Pivot or zip a seq<seq<'a>> in F#
f#, functional-programming, pivot, sequence
Solution
If you're going for a solution which is semantically Seq, you're going to have to stay lazy all the time.
let zip seq = seq
|> Seq.collect(fun s -> s |> Seq.mapi(fun i e -> (i, e))) //wrap with index
|> Seq.groupBy(fst) //group by index
|> Seq.map(fun (i, s) -> s |> Seq.map snd) //unwrap
Test:
let seq = Enumerable.Repeat((seq [1; 2; 3]), 3) //don't want to while(true) yield. bleh.
printfn "%A" (zip seq)
Output:
seq [seq [1; 1; 1]; seq [2; 2; 2]; seq [3; 3; 3]]
Problem
Let's say I have a sequence of sequences, e.g. ``` {1, 2, 3}, {1, 2, 3}, {1, 2, 3} ``` What is the best way to pivot or zip this sequence so I instead have, ``` {1, 1, 1}, {2, 2, 2}, {3, 3, 3} ``` Is there a comprehensible way of doing so without resorting to manipulation of the underlying `IEnumerator<_>` type? To clarify, these are `seq<seq<int>>` objects. Each sequences (both internal and external) can have any number of items.