Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivot or zip a seq<seq<'a>> in F#

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.

like image 967
GregRos Avatar asked Oct 07 '12 06:10

GregRos


3 Answers

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]]
like image 118
Asti Avatar answered Oct 18 '22 06:10

Asti


This seems very inelegant but it gets the right answer:

(seq [(1, 2, 3); (1, 2, 3); (1, 2, 3);]) 
|> Seq.fold (fun (sa,sb,sc) (a,b,c) ->a::sa,b::sb,c::sc) ([],[],[]) 
|> fun (a,b,c) -> a::b::c::[]
like image 32
John Palmer Avatar answered Oct 18 '22 08:10

John Palmer


It looks like matrix transposition.

let data =
    seq [
        seq [1; 2; 3]
        seq [1; 2; 3]
        seq [1; 2; 3]
    ]

let rec transpose = function
    | (_::_)::_ as M -> List.map List.head M :: transpose (List.map List.tail M)
    | _ -> []

// I don't claim it is very elegant, but no doubt it is readable
let result =
    data
    |> List.ofSeq
    |> List.map List.ofSeq
    |> transpose
    |> Seq.ofList
    |> Seq.map Seq.ofList

Alternatively, you may adopt the same method for seq, thanks to this answer for an elegant Active pattern:

let (|SeqEmpty|SeqCons|) (xs: 'a seq) =
  if Seq.isEmpty xs then SeqEmpty
  else SeqCons(Seq.head xs, Seq.skip 1 xs)

let rec transposeSeq = function
    | SeqCons(SeqCons(_,_),_) as M ->
        Seq.append
            (Seq.singleton (Seq.map Seq.head M))
            (transposeSeq (Seq.map (Seq.skip 1) M))
    | _ -> Seq.empty

let resultSeq = data |> transposeSeq

See also this answer for technical details and two references: to PowerPack's Microsoft.FSharp.Math.Matrix and yet another method involving mutable data.

like image 27
bytebuster Avatar answered Oct 18 '22 08:10

bytebuster