旋转或压缩seq <seq <'a>&gt;在F#</seq <'a>

时间:2012-10-07 06:12:18

标签: f# functional-programming pivot sequence

假设我有一系列序列,例如

{1, 2, 3}, {1, 2, 3}, {1, 2, 3}

透视或拉链此序列的最佳方法是什么,所以我改为

{1, 1, 1}, {2, 2, 2}, {3, 3, 3}

在不诉诸操纵基础IEnumerator<_>类型的情况下,是否有一种易于理解的方式?

澄清一下,这些是seq<seq<int>>个对象。每个序列(内部和外部)可以包含任意数量的项目。

4 个答案:

答案 0 :(得分:3)

如果你想要一个语义上为Seq的解决方案,你将不得不一直保持懒惰。

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

测试:

let seq =  Enumerable.Repeat((seq [1; 2; 3]), 3) //don't want to while(true) yield. bleh.
printfn "%A" (zip seq)

输出:

seq [seq [1; 1; 1]; seq [2; 2; 2]; seq [3; 3; 3]]

答案 1 :(得分:1)

这似乎非常不优雅,但它得到了正确的答案:

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

答案 2 :(得分:1)

看起来像矩阵换位。

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

或者,您可以对seq采用相同的方法,感谢this answer优雅的活动模式:

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

另请参阅this answer了解技术详情和两个参考: PowerPack Microsoft.FSharp.Math.Matrix以及另一种涉及可变数据的方法。

答案 3 :(得分:0)

这与@Asti的答案相同,只是稍微清理了一下:

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