2011-11-06 54 views
1

我有4个不同数据的数组。对于字符串的第一个数组,我想删除重复的元素并获得具有4个元素的唯一元组数组的结果。查找元组的唯一数组

例如,假设数组是:

let dupA1 = [| "A"; "B"; "C"; "D"; "A" |] 

let dupA2 = [| 1; 2; 3; 4; 1 |] 

let dupA3 = [| 1.0M; 2.0M; 3.0M; 4.0M; 1.0M |] 

let dupA4 = [| 1L; 2L; 3L; 4L; 1L |] 

我想要得到的结果是:

let uniqueArray = [| ("A", 1, 1.0M, 1L); ("B", 2, 2.0M, 2L); ("C", 3, 3.0M, 3L); ("D",4, 4.0M, 4L) |] 
+0

所以,你要为每件商品一起压缩呢?如果数组包含不同数量的项目会怎样? – abatishchev

+0

您检查了(V标记)我的答案。如果你想给拉蒙的答案,你现在可以改变它。 – BLUEPIXY

回答

3
let zip4 s1 s2 s3 s4 = 
    Seq.map2 (fun (a,b)(c,d) ->a,b,c,d) (Seq.zip s1 s2)(Seq.zip s3 s4) 

let uniqueArray = zip4 dupA1 dupA2 dupA3 dupA4 |> Seq.distinct |> Seq.toArray 
4

首先你需要写一个ZIP4功能,这将压缩数组:

// the function assumes the 4 arrays are of the same length 
let zip4 a (b : _ []) (c : _ []) (d : _ []) = 
    Array.init (Array.length a) (fun i -> a.[i], b.[i], c.[i], d.[i]) 

然后为数组使用Seq.distinct

let distinct s = Seq.distinct s |> Array.ofSeq 

其结果将是:

> zip4 dupA1 dupA2 dupA3 dupA4 |> distinct;; 
val it : (string * int * decimal * int64) [] = 
    [|("A", 1, 1.0M, 1L); ("B", 2, 2.0M, 2L); ("C", 3, 3.0M, 3L); 
    ("D", 4, 4.0M, 4L)|] 
+0

非常感谢。实际上,我真正的问题有8个不同数据类型的数组,因为我不知道如何编写Zip4这样的代码,因为F#最多只有zip3;那么我很难找出如何找到独特的元组数组。 –