ocamlml

OCaml physical and structural equality


I understading than x == y is false because each is instantiated in different memory locations (https://stackoverflow.com/a/1412688/11439260). But i expected than a == b is false. Why this is true? How can I verify that there are two different let bindings?

(* First Examplle *)
let x = "odg"
let y = "odg"

x = y (* true *)
x == y (* false *)

(* Second example *)
let a = 1
let b = 1

a == b (* true, WHY? *)

Solution

  • One way to think of physical equality (==) is that it compares the addresses of the given values. Values in different memory locations have different addresses and will be physically unequal even if their values are structurally the same.

    However an int is an immediate value in your OCaml implementation. In other words, there is no address involved. The int itself appears (in a tagged format) where you might expect the address to go. This means that any two ints that are structurally equal (=) are also physically equal (==).

    Another way to say this is that ints aren't boxed (in your implementation and in all the ones I've seen).

    Other integral values are boxed. (Note that 44l = 44 L, an int32 constant):

    # 44l;;
    - : int32 = 44l
    # 44l = 44l;;
    - : bool = true
    # 44l == 44l;;
    - : bool = false
    

    Edit

    As @octachron says, you really shouldn't write code that uses physical equality (==) on immutable values.

    There is no guarantee about the behavior of == on immutable values other than that a == b implies a = b.