Why is Ocaml false "1.0 == 1.0"?

Why does 1 == 1 return true and 1.0 == 1.0 returns false?

I think = is structural and == is physical, so shouldn't both return false?

+6
source share
2 answers

The problem is not the values, the problem is the physical equality == . Its meaning is implementation dependent, with the exception of certain specific warranties.

In a typical OCaml implementation, floating values ​​are inserted into the box, so it is normal if no two float values ​​are physically equal.

Conversely, int values ​​are not placed in the box, so two equal int values ​​will be physically equal.

Physical equality cannot be used unless you are sure you know what you are doing. It violates many of the desired properties of a functional language, such as referential transparency, as in this case.

Update : specific guarantees for the value == are given by Pierre Chambard in his excellent answer.

+11
source

Semantics of physical equality (==):

  • for any value x == y truly means that compare xy is 0 (which usually means x = y)
  • by mutable values, if x == y is true if and only if the mutation x also affects y

That's all, don’t assume anything else. (see { http://caml.inria.fr/pub/docs/manual-ocaml-4.02/libref/Pervasives.html#VAL%28==%29 }

Note that compare xy = 0 not quite equivalent to x = y , because nan not equal to anything, including itself

(by the way, since Ocaml 4.02 optimization makes 1.0 == 1.0 true in native code, but not in bytecode)

+9
source

Source: https://habr.com/ru/post/975377/


All Articles