Does != have meaning in OCaml?
you have experienced the difference between structural and physical equality.
<>
is to =
(structural equality) as !=
is to ==
(physical equality)
"odg" = "odg" (* true *)
"odg" == "odg" (* false *)
is false because each is instantiated in different memory locations, doing:
let v = "odg"
v == v (* true *)
v = v (* true *)
Most of the time you'll want to use =
and <>
.
edit about when structural and physical equality are equivalent:
You can use the what_is_it function and find out all the types that would be equal both structurally and physically. As mentioned in the comments below, and in the linked article, characters, integers, unit, empty list, and some instances of variant types will have this property.
The opposite for !=
operator is ==
operator, not the =
one.
# "a" != "a" ;;
- : bool = true
# "a" == "a" ;;
- : bool = false
The == operator is a "physical equality". When you type "a" == "a"
, you compare two different instances of strings that happen to look alike, so the operator returns false
. While having one instance makes it return true:
# let str = "a"
in str == str ;;
- : bool = true
# let str = "a"
in str != str ;;
- : bool = false
A quick explanation about ==
and !=
in OCaml in addition to all the correct answers that have already been provided:
1/ ==
and !=
expose 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 []|]
# x == t.(0) ;;
- : bool = true
So far, so good: x
and t.(0)
are physically equal because t.(0)
contains a pointer to the same block that x
is pointing to. This is what basic knowledge of the implementation dictates. BUT:
# let x = 1.125 ;;
val x : float = 1.125
# let t = Array.create 1 x ;;
val t : float array = [|1.125|]
# x == t.(0) ;;
- : bool = false
What you are seeing here are the results of an otherwise useful optimization involving floats.
2/ On the other hand, there is a safe way to use ==
, and that is as a quick but incomplete way to check for structural equality.
If you are writing an equality function on binary trees
let equal t1 t2 =
match ...
checking t1
and t2
for physical equality is a quick way to detect that they are obviously structurally equal, without even having to recurse and read them. That is:
let equal t1 t2 =
if t1 == t2
then true
else
match ...
And if you keep in mind that in OCaml the “boolean or” operator is “lazy”,
let equal t1 t1 =
(t1 == t2) ||
match ...