简体   繁体   中英

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

Let's say I have a sequence of sequences, eg

{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.

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

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

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 .

This is the same answer as @Asti, just cleaned up a little:

[[1;2;3]; [1;2;3]; [1;2;3]] 
    |> Seq.collect Seq.indexed 
    |> Seq.groupBy fst 
    |> Seq.map (snd >> Seq.map snd);;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM