LargeLizard
LargeLizard

Reputation: 66

Match always succeeds when dereferencing pointer OCaml

My code is the following

let newObj (s) : someObj = 
   let myStr = ref s in
   let myInt = ref 0 in {
       someFun = (fun newS ->
           match !myStr with
           | newS -> true
           | _ -> false
   }
;;

I have tested this code

let test = newObj "right";;
test.someFun "right";;
test.someFun "wrong";;

Both calls to someFun return true.

I have also tried

if (!mystr = newS) then true else false

and this works. Why?

Upvotes: 0

Views: 56

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66793

The meaning of an identifier in a pattern is not what you seem to think. Any identifier that appears in a pattern is a new occurrence of the id that will be bound to whatever value is matched. So, this match:

       match !myStr with
       | newS -> true
       | _ -> false

will always match on the first case. It binds the identifier newS to the value !myStr; however this has no visible effect since you don't use newS in the associated expression.

The newS in the pattern has nothing to do with any previous appearance of the identifier newS. This is a new use of the identifier.

That's why the if statement works. It is referring to the existing binding of the identifier (there's no pattern involved).

As I side comment, when I enter the expression above, the compiler warns me as follows:

Warning 11: this match case is unused.

The compiler is pointing out that the second branch of the match will never be used. The first branch always matches.

It's good to pay attention to warnings like this.

Upvotes: 5

Related Questions