OCaml boolean expression [[]] == [[]]
Asked Answered
F

2

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.

Frae answered 4/4, 2012 at 10:36 Comment(1)
There is more information on structural and physical equality in another question, https://mcmap.net/q/280727/-does-have-meaning-in-ocamlCorporate
F
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
Farouche answered 4/4, 2012 at 11:26 Comment(0)
R
9

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

Rondel answered 4/4, 2012 at 10:57 Comment(4)
Ok I undertstand now. But it means that the first [[]] is 'a list list and the second 'b list list ?Frae
Yes, each [] allocates a new list (c.f. cs.jhu.edu/~scott/pl/lectures/caml-intro.html), but both list are not the very same list.Rondel
[] 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, [[]] = ([] :: []).Corporate
@nlucaroni: Actually, I referred to the outer brackets. Thank you to clear this point.Rondel

© 2022 - 2024 — McMap. All rights reserved.