获取 F# 中两个整数列表之间的匹配数

Get number of matches between two integer lists in F#

我有两个整数列表(这里是 1 和 0,但可以是任何整数):

List1 : [1; 1; 1; 1]
List2 : [0; 0; 1; 0]

我想计算两个列表在值和位置上的匹配数。所以,在这种情况下,只有一个匹配项,在第 3 个位置。

在 C# 中,我会使用 for 循环来解决这个问题,如下所示:

int matches = 0;
for (int i = 0; i < list1.Count; i++)
{
    if (list1[i] == list2[i])
        matches++;
}

但我想知道在 F# 中是否有更好的方法。

这是我的做法:

let l1 = [1; 0; 1; 1];;                                                                               
let l2 = [0; 0; 1; 0];;                                                                               

let sumMatches ns ms = 
   List.zip ns ms 
   |> List.map (fun (n,m) -> if n=m then 1 else 0) 
   |> List.sum

> sumMatches l1 l2;;                                                               
val it : int = 2   

这是 filterlength 的替代方案:

let sumMatches ns ms = 
   List.zip ns ms 
   |> List.filter (fun (n,m) -> n=m) 
   |> List.length

备注

如果您有非常大的列表,那么您应该

  • 使用 Seq. 而不是 List.(因为 List 模块函数将创建中间列表)
  • 按照 Lee 的建议使用 Seq.map2

在这个变体中:

let sumMatches ns ms = 
   Seq.map2 (fun n m -> if n = m then 1 else 0) ns ms 
   |> Seq.sum 

如果你真的也需要速度,那么你应该像在 C# 中那样做(使用 for 循环和可变计数器)

但这通常没什么大不了的。

替代方法 - 使用 List.fold2:

let l1 = [1; 0; 1; 1]                                                                             
let l2 = [0; 0; 1; 0]

let sumMatches ns ms = List.fold2 (fun acc n m -> acc + if n = m then 1 else 0) 0 ns ms

sumMatches l1 l2  |> printfn "Count = %i"

打印:

Count = 2

Link: https://dotnetfiddle.net/pe9fOY