Does != have meaning in OCaml?

前端 未结 5 1704
抹茶落季
抹茶落季 2020-12-07 22:50

It seems to be an equivalency comparison for some types, but not strings.

# 3 != 3;;
- : bool = false
# 3 != 2;;
- : bool = true

This is as

5条回答
  •  孤城傲影
    2020-12-07 22:58

    A quick explanation about == and != in OCaml in addition to all the correct answers that have already been provided:

    1/ == and != expose implementation details that you really don't want to know about. Example:

    # let x = Some [] ;;
    val x : 'a list option = Some []
    # let t = Array.create 1 x ;;
    val t : '_a list option array = [|Some []|]
    # x == t.(0) ;;
    - : bool = true
    

    So far, so good: x and t.(0) are physically equal because t.(0) contains a pointer to the same block that x is pointing to. This is what basic knowledge of the implementation dictates. BUT:

    # let x = 1.125 ;;
    val x : float = 1.125
    # let t = Array.create 1 x ;;
    val t : float array = [|1.125|]
    # x == t.(0) ;;
    - : bool = false
    

    What you are seeing here are the results of an otherwise useful optimization involving floats.

    2/ On the other hand, there is a safe way to use ==, and that is as a quick but incomplete way to check for structural equality.

    If you are writing an equality function on binary trees

    let equal t1 t2 =
      match ...
    

    checking t1 and t2 for physical equality is a quick way to detect that they are obviously structurally equal, without even having to recurse and read them. That is:

    let equal t1 t2 =
      if t1 == t2
      then true
      else 
        match ...
    

    And if you keep in mind that in OCaml the “boolean or” operator is “lazy”,

    let equal t1 t1 =
      (t1 == t2) ||
      match ...
    

提交回复
热议问题