Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ocaml same string unequaled

I am an Ocaml learner.
And 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" sould be equal to "123" but output this:

123
123
fail

"123" was not equal "123"…
why and how to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The is_int_clear function is comparing the original string x with the result of applying clear_int to it, which is targ. However, the == operator in OCaml compares whether two values are the same object in memory, rather than whether they are equal in value.

To compare two values for equality in OCaml, you can use the = operator. This operator will compare the values of the two operands, rather than whether they are the same object in memory.

To fix this issue, you can simply replace == with = in the is_int_clear function, like this:

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

With this change, the is_int_clear function should return true when given the string "123", and the program should print succ to the console.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading