2

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? *)
aspeddro
  • 87
  • 3

2 Answers2

5

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.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
4

Another important point is that physical equality is not specified for immutable values. The result of

let xl = [0]
let yl = [0]
let whatever = xl == yl

will depend on how the code was compiled (or interpreted), and more generally on which compiler optimizations were applied or not. Typically with recent versions of OCaml, your string example x==y may return true because string are immutable by default since OCaml 4.06 .

In other words, you cannot use == to determine if two values were defined with the same bindings or not, because this notion is no part of the OCaml language and is not preserved by compiler optimizations.

octachron
  • 17,178
  • 2
  • 16
  • 23