Caml 中函数的物理相等性测试
Physical equality test for functions in Caml
在 Caml 中,运算符 ==
测试相同类型的两个值之间的物理相等性。它可以特别用于以这种方式比较函数。
例如有一个
# print_string == print_string;;
- : bool = true
但是,令人惊讶的是,
# (==) == (==);;
- : bool = false
这个表达式应该计算成 true
。
你能解释一下这种行为吗?
==
的行为在 Pervasives 模块中定义:
e1 == e2 tests for physical equality of e1 and e2. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, e1 == e2 is true if and only if physical modification of e1 also affects e2. On non-mutable types, the behavior of ( == ) is implementation-dependent; however, it is guaranteed that e1 == e2 implies compare e1 e2 = 0
由于函数不可变,唯一的保证是如果它们与 ==
比较相等,它们也将与 compare
比较相等。由于不能保证函数与 compare
具有可比性,这实质上意味着 ==
对于比较函数根本没有用。
# compare (==) (==);;
Exception: Invalid_argument "equal: functional value".
If ==
returns false
对于不可变值,根本没有任何保证。这意味着对于任何不可变值,==
可以随时自由地 return false
。所以在你的第二个例子中 return false
并没有什么不妥。
在 Caml 中,运算符 ==
测试相同类型的两个值之间的物理相等性。它可以特别用于以这种方式比较函数。
例如有一个
# print_string == print_string;;
- : bool = true
但是,令人惊讶的是,
# (==) == (==);;
- : bool = false
这个表达式应该计算成 true
。
你能解释一下这种行为吗?
==
的行为在 Pervasives 模块中定义:
e1 == e2 tests for physical equality of e1 and e2. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, e1 == e2 is true if and only if physical modification of e1 also affects e2. On non-mutable types, the behavior of ( == ) is implementation-dependent; however, it is guaranteed that e1 == e2 implies compare e1 e2 = 0
由于函数不可变,唯一的保证是如果它们与 ==
比较相等,它们也将与 compare
比较相等。由于不能保证函数与 compare
具有可比性,这实质上意味着 ==
对于比较函数根本没有用。
# compare (==) (==);;
Exception: Invalid_argument "equal: functional value".
If ==
returns false
对于不可变值,根本没有任何保证。这意味着对于任何不可变值,==
可以随时自由地 return false
。所以在你的第二个例子中 return false
并没有什么不妥。