A brief description of == and != In OCaml in addition to all the correct answers that have already been provided:
1 / == and != Reveal implementation details that you really don't want to know about. Example:
# let x = Some [] ;; val x : 'a list option = Some [] # let t = Array.create 1 x ;; val t : '_a list option array = [|Some []|]
So far, so good: x and t.(0) physically equal, because t.(0) contains a pointer to the same block that x points to. This is what basic implementation knowledge dictates. BUT:
# let x = 1.125 ;; val x : float = 1.125
What you see here are the results of a useful optimization involving floats.
2 / On the other hand, there is a safe way to use == , and it is a quick but incomplete way to check for structural equality.
If you write an equality function on binary trees
let equal t1 t2 = match ...
checking t1 and t2 for physical equality is a quick way to find that they are obviously structurally equal, without even requiring a second review and reading. I.e:
let equal t1 t2 = if t1 == t2 then true else match ...
And if you remember that in OCaml the "logical or" operator is "lazy",
let equal t1 t1 = (t1 == t2) || match ...
Pascal Cuoq Sep 13 '09 at 9:24 2009-09-13 09:24
source share