如何检查 OCaml 中的两个地图是否相等

How do I check if two Maps are equal in OCaml

无论顺序如何,您如何检查 OCaml 中的两个映射是否相等?

例如:

地图 1 :

var1 ->  [Neg]

var2 ->  [Pos; Zero; Neg]

var3 ->  [Neg; Pos]

地图2:

var1 ->  [Neg]

var2 ->  [Pos; Zero; Neg]

var3 ->  [Pos; Neg]

我尝试过的:

Map.equal (fun x y -> x = y)

这 returns 错误,因为它认为顺序很重要。

我应该对列表进行排序,还是有更有效的功能方式?

谢谢

Map.equal 的文档说:

equal cmp m1 m2 tests whether the maps m1 and m2 are equal, that is, contain equal keys and associate them with equal data. cmp is the equality predicate used to compare the data associated with the keys.

您明确要求使用 = 作为您的等式谓词,但您也说这不是您想要的。

解决方案是提供您确实需要的相等谓词。

如果你想知道两个列表是否包含相同的元素而不考虑顺序,你可以对列表进行排序并比较排序后的值。

let equal_contents a b =
    List.sort compare a = List.sort compare b

您还可以按规范顺序(即排序)保留地图中的值。然后你上面给出的代码就可以工作了。