“等于 (=)" 和有什么不一样?和“相同(==)"在ocaml? [英] What's the difference between "equal (=)" and "identical (==)" in ocaml?
问题描述
在OCaml
中,我们有两种股权比较
:
x = y
和 x == y
,
那么它们之间的确切区别是什么?
So what's exact the difference between them?
ocaml 中的 x = y
和 Java 中的 x.equals(y)
一样吗?
Is that x = y
in ocaml just like x.equals(y)
in Java?
and x == y
就像Java中的x == y(比较地址)
?
and x == y
just like x == y (comparing the address)
in Java?
推荐答案
我不知道 x.equals(y)
在 Java 中究竟是如何工作的.如果它进行深度"比较,则类比非常接近.需要注意的一件事是,物理平等在 OCaml(以及一般的函数式语言)中是一个模糊的概念.编译器和运行时系统将移动值,并且可以随意合并和取消合并纯(非可变)值.所以你应该只使用 ==
如果你真的知道你在做什么.在某种程度上,它需要熟悉实现(除非必要,否则应避免这种情况).
I don't know exactly how x.equals(y)
works in Java. If it does a "deep" comparison, then the analogy is pretty close. One thing to be careful of is that physical equality is a slippery concept in OCaml (and functional languages in general). The compiler and runtime system are going to move values around, and may merge and unmerge pure (non-mutable) values at will. So you should only use ==
if you really know what you're doing. At some level, it requires familiarity with the implementation (which is something to avoid unless necessary).
OCaml 为 ==
做出的具体保证是弱的.可变值在物理上以您期望的方式进行比较(即,如果改变两者之一实际上也会改变另一个).但是对于非可变值,唯一的保证是比较物理上相等的值 (==
) 也将比较相等 (=
).请注意,正如 sepp2k 指出的浮动值所指出的那样,相反的情况不为真.
The specific guarantees that OCaml makes for ==
are weak. Mutable values compare as physically equal in the way you would expect (i.e., if mutating one of the two will actually mutate the other also). But for non-mutable values, the only guarantee is that values that compare physically equal (==
) will also compare as equal (=
). Note that the converse is not true, as sepp2k points out for floating values.
本质上,对于非可变值,语言规范告诉您的是,您可以使用 ==
作为快速检查来确定两个非可变值是否相等(=
).如果它们在物理上比较相等,则它们在价值方面是相等的.如果它们在物理上不相等,则您不知道它们在价值方面是否相等.您仍然必须使用 =
来决定.
In essence, what the language spec is telling you for non-mutable values is that you can use ==
as a quick check to decide if two non-mutable values are equal (=
). If they compare physically equal, they are equal value-wise. If they don't compare physically equal, you don't know if they're equal value-wise. You still have to use =
to decide.
这篇关于“等于 (=)" 和有什么不一样?和“相同(==)"在ocaml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!