F#比较元组的数组并返回不同的元素和索引

时间:2011-10-26 16:19:35

标签: f#

#light

let a1 = [| (1, 1); (2, 1); (3, 1) |]

let a2 = [| (1, 1); (2, 3); (3, 1) |]

let aa = Array.zip a1 a2
       |> Array.filter(fun (x, y) -> x <> y)

我想编写一个函数来执行此操作:它将从两个数组返回不同的元组,但我还想返回第二个数组中不同元组的索引和第二个数组中的相应元组。 (我的代码完全不起作用!) 对于我上面的例子,我想返回:1和(2,3) 另一个例子:

let a1 = [| (1, 1); (2, 1); (3, 1); (4, 1) |]

let a2 = [| (1, 1); (2, 3); (3, 1); (4, 2) |]

我想要回归:1和(2,3); 3和(4,2) 如果您有任何想法,请告诉我您的代码。 此外,我不习惯F#的新地方,格式让我觉得很难找到一个发布我的问题的好地方,因此,我仍然在这里发表我的问题。

3 个答案:

答案 0 :(得分:4)

let a1 = [| (1, 1); (2, 1); (3, 1) |]

let a2 = [| (1, 1); (2, 3); (3, 1) |]

let diff = 
    (a1, a2) 
    ||> Array.mapi2(fun i t1 t2 -> (i, t1, t2))
    |> Array.choose(fun (i, a, b) -> if a <> b then Some (i, b) else None)

答案 1 :(得分:0)

这是一种方法:

let diff a b =
  let s = Set.ofSeq a
  b 
  |> Seq.mapi (fun i x -> i, x)
  |> Seq.filter (fun (_, x) -> not (Set.contains x s))

实施例

let a1 = [| (1, 1); (2, 1); (3, 1) |]
let a2 = [| (1, 1); (2, 3); (3, 1) |]
diff a1 a2 //output: seq [(1, (2, 3))]

这适用于任何集合(listarrayseq<_>set等),并且序列可能具有不同的长度。如果你知道你将永远使用相同长度的数组,你可以相应地进行优化(参见desco的答案)。

答案 2 :(得分:0)

let diff (a:(int * int)[]) b =
  b
  |> Array.mapi (fun i tp -> if a.[i] <> tp then (i, tp) else (-1, tp))
  |> Array.filter (fun (x, _) -> x >= 0) 

<强>样本

 > diff a1 a2;;
val it : (int * (int * int)) [] = [|1, (2, 3)); (3, (4, 2))|]