【问题标题】:Unexpected string equality resultsUnexpected string equality results
【发布时间】:2022-12-01 23:56:36
【问题描述】:

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?

【问题讨论】:

  • Style note: when you are aliasing functions in this example, examples like let soi x = string_of_int x can be witten as let soi = string_of_int but even then, it's questionable whether thishelpsor actually just makes your code slightly more difficult to understand.

标签: ocaml equality


【解决方案1】:

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.

【讨论】:

    猜你喜欢
    • 2019-10-06
    • 2012-11-26
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多