Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "1.0 == 1.0" false in Ocaml?

Tags:

equality

ocaml

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

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

like image 443
user3340037 Avatar asked Sep 16 '14 21:09

user3340037


2 Answers

The problem isn't with the values, the problem is with physical equality ==. Its meaning is implementation-dependent except for certain specific guarantees.

In the usual OCaml implementation, floating values are boxed, so it's normal for no two values of type float to be physically equal.

Conversely, int values are not boxed, so two equal int values will be physically equal.

Physical equality should not be used unless you're very sure you know what you're doing. It violates many desired properties of a functional language, such as referential transparency, as in this case.

Update: the specific guarantees for the meaning of == are given by Pierre Chambart in his excellent answer.

like image 126
Jeffrey Scofield Avatar answered Sep 18 '22 15:09

Jeffrey Scofield


The semantics of physical equality (==) is:

  • on any value x == y is true implies compare x y is 0 (which usualy means x = y)
  • on mutable values if x == y is true if and only if, mutating x will also affect y

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

Note that compare x y = 0 is not exactly equivalent to x = y because nan is not equal to nothing, including itself

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

like image 27
Pierre Chambart Avatar answered Sep 17 '22 15:09

Pierre Chambart