6

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

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

旋转或压缩这个序列的最佳方式是什么,所以我有,

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

有没有一种可以理解的方式来做到这一点而不诉诸于操纵底层IEnumerator<_>类型?

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

4

4 回答 4

4

如果您要寻求语义 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]]
于 2012-10-07T10:33:35.623 回答
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::[]
于 2012-10-07T06:40:34.247 回答
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,这要感谢这个优雅的 Active 模式的答案:

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

另请参阅此答案以获取技术细节和两个参考:PowerPack和涉及mutable dataMicrosoft.FSharp.Math.Matrix另一种方法。

于 2012-10-07T07:21:24.107 回答
1

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

[[1;2;3]; [1;2;3]; [1;2;3]] 
    |> Seq.collect Seq.indexed 
    |> Seq.groupBy fst 
    |> Seq.map (snd >> Seq.map snd);;
于 2016-08-31T15:45:00.060 回答