比较非 int 类型的相等运算符

Equality operator to compare non int types

我最近将我的项目从 OCaml 4.03 更新到 OCaml 4.13。一个变化是我在检查非 int 类型之间的相等性时遇到类型错误。例如,对于 floats 我得到这个:

错误:此表达式的类型为 float,但表达式应为 int

我可以通过显式使用 Float.(f0 = f1) 来解决这个问题。但是我在自定义类型方面遇到了同样的问题。例如:

utop # type e = X | Y
utop # let a = X;;
val a : e = X
utop # let b = Y;;
utop # X = Y;;
Error: This expression has type e but an expression was expected of type int

处理这种情况的正确方法是什么? Stdlib.(a = b) 可行,但感觉很麻烦,因为多态相等运算符是如此常用。

这不是 OCaml 的固有行为。它来自 Jane Street Base(可能还有来自 Jane Street 的其他模块),它覆盖了一些 built-in 多态函数。

我们的想法是,built-in 多态比较存在风险,如果您不小心,可能会大吃一惊。

要获得常用的 OCaml 多态比较运算符,您可以使用 Polymorphic_compare 模块。这是 Jane Street Base 文档的 link(如果您使用的是它):Base at Jane Street