tags:

views:

74

answers:

1

From what I can tell, = and != is supposed to work on strings in OCAML. I'm seeing strange results though which I would like to understand better.

When I compare two strings with = I get the results I expect:

# "steve" = "steve";;
- : bool = true
# "steve" = "rowe";;
- : bool = false

but when I try != I do not:

# "steve" != "rowe";;
- : bool = true
# "steve" != "steve";; (* unexpected - shouldn't this be false? *)
- : bool = true

Can anyone explain? Is there a better way to do this?

+8  A: 

!= is not the negation of =. <> is the negation of = that you should use:

# "steve" <> "rowe" ;;
- : bool = true
# "steve" <> "steve" ;;
- : bool = false
# 

!= is the negation of ==, and if you are an OCaml beginner, you should not be using any of these two yet. They can be a little tricky, and they are officially underspecified (the only guarantee is that if two values are == they are =).

Pascal Cuoq
I am a beginner. That makes a lot of sense. Thank you very much.
Steve Rowe
`!=` and `==` implement "physical equality", which means that for any "boxed" type (i.e. reference types, anything except int, char, bool), it compares whether they are the same instance (i.e. their addresses are the same), not whether their values are the same`# 3.14 == 3.14;;``- : bool = false`
newacct
A question awhile ago covers some subtleties. http://stackoverflow.com/questions/1412668/does-have-meaning-in-ocaml
nlucaroni