What's the difference between "equal (=)" and "identical (==)" in ocaml?

Jackson Tale picture Jackson Tale · Nov 27, 2012 · Viewed 23.8k times · Source

In OCaml, we have two kinds of equity comparisons:

x = y and x == y,

So what's exact the difference between them?

Is that x = y in ocaml just like x.equals(y) in Java?

and x == y just like x == y (comparing the address) in Java?

Answer

Jeffrey Scofield picture Jeffrey Scofield · Nov 27, 2012

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).

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.