16

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?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Steve Rowe
  • 19,411
  • 9
  • 51
  • 82

1 Answers1

19

!= 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
  • 79,187
  • 7
  • 161
  • 281
  • 2
    A question awhile ago covers some subtleties. http://stackoverflow.com/questions/1412668/does-have-meaning-in-ocaml – nlucaroni Jun 17 '10 at 22:05