Search code examples
ocamlequality

Unexpected string equality results


I have some OCaml code:

let (&>) : ('x -> 'y) -> ('y -> 'z) -> ('x -> 'z) =
   fun g f x -> x |> g |> f

let soi x = string_of_int x
let sof x = string_of_float x
let fos x = float_of_string x
let ios x = int_of_string x

let clear_int = ios &> soi

let is_int_clear (x: string) = 
  let targ = clear_int x in
  let _ = print_endline x in
  let _ = print_endline targ in
  x == targ

let ccc = is_int_clear "123"

let scc = if ccc then "succ" else "fail"

let () = print_endline scc

I think "123" should be equal to "123" but output this:

123
123
fail

"123" was not equal "123".

Why and how to fix it?


Solution

  • The fault in your logic lies in using == which tests for physical equality. This is checking that the two strings reside at the same location in memory.

    You wanted to use = which tests for structural equality: whether the two values contain the same information.

    The change is very simple.

    let is_int_clear (x: string) = 
      let targ = clear_int x in
      let _ = print_endline x in
      let _ = print_endline targ in
      x = targ