我有一个 foo: seq<int*int>
我想拆分元组项,然后将结果存储到两个变量中,每个变量是 seq<int>
我想知道是否有更漂亮的方法来做到这一点,例如
let item1, item2 = foo |> ?????
我目前的解决方案:
let item1 = foo |> Seq.map(fun (f1,_) -> f1)
let item2 = foo |> Seq.map(fun (_,f2) -> f2)
最佳答案
可悲的是,没有插入Seq.unzip
函数包含在语言中,尽管列表 ( List.unzip
) 和数组 ( Array.unzip
) 的等效项确实存在。
有几种方法可以定义这样的函数,一种方法是:
let unzip sequence =
let (lstA, lstB) =
Seq.foldBack (fun (a,b) (accA, accB) ->
a::accA, b::accB) sequence ([],[])
(Seq.ofList lstA, Seq.ofList lstB)
或者,如果您不关心在列表之间来回切换,您可以这样做:
let item1, item2 =
let it1, it2 =
foo
|> List.ofSeq
|> List.unzip
(Seq.ofList it1, Seq.ofList it2)
关于f# - 如何做 Seq.unzip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034919/