8

I have a function that return [[]], and I want to test the result as unit test. But I found that the expression [[]] == [[]] return false. Here a simple test code:

# [[]] == [[]];;
- : bool = false

Can someone explain me why this expression is evaluated as false?

Thanks.

pad
  • 41,040
  • 7
  • 92
  • 166
Atikae
  • 177
  • 1
  • 8
  • There is more information on structural and physical equality in another question, http://stackoverflow.com/questions/1412668/does-have-meaning-in-ocaml/ – nlucaroni Apr 04 '12 at 21:30

2 Answers2

13

Use = since you have structural equality for comparing two values:

# [[]] = [[]];;
- : bool = true

Because == is reference equality, it only returns true if you refer to the same memory location:

let a = [[]]
let b = a

# b == a;;
- : bool = true
pad
  • 41,040
  • 7
  • 92
  • 166
9

The == operator in OCaml means "physical equality". However, you have two (physically) different lists. Probably, you want "structural equality", which is tested by =.

Ellie Kesselman
  • 899
  • 1
  • 17
  • 34
Matthias
  • 8,018
  • 2
  • 27
  • 53
  • Ok I undertstand now. But it means that the first [[]] is 'a list list and the second 'b list list ? – Atikae Apr 04 '12 at 11:02
  • 1
    Yes, each `[]` allocates a new list (c.f. http://www.cs.jhu.edu/~scott/pl/lectures/caml-intro.html), but both list are not the *very same* list. – Matthias Apr 04 '12 at 11:11
  • 2
    `[]` has structural and physical equality (it's integer-like). It does not allocate a new list. It's the outer brackets that are creating the new list, since, `[[]] = ([] :: [])`. – nlucaroni Apr 04 '12 at 21:35
  • 1
    @nlucaroni: Actually, I referred to the outer brackets. Thank you to clear this point. – Matthias Apr 05 '12 at 03:50