Skip to content

Issues with compare primitives #6040

Closed
@glennsl

Description

@glennsl

While trying to figure out some unexpected behavior with NaNs, I've discovered the following:

  1. Caml_obj uses Caml.int_compare to compare numbers, both ints and floats.
  2. Caml.int_compare considers NaN > NaN and any other value. (which is of course fine if it's never used on NaNs, but it is)
  3. Caml.float_compare considers NaN == NaN.
  4. Caml.float_compare considers NaN less than any other value.
  5. Caml.obj.lessthan and Caml_obj.greatherthan uses Caml_obj.compare, and therefore also considers NaN the greatest of all values! This is inconsistent with both OCaml and JavaScript behaviour. Comparing NaN to anything, in any way, should return false.

Simple repro:

// These will all print true

Js.log(compare(nan, nan) == 0) // Caml.float_compare
Js.log(compare(nan, 33.3) == -1) // Caml.float_compare
Js.log(compare(nan->Obj.magic, nan->Obj.magic) == 1) // Caml_obj.compare (which in turn uses Caml.int_compare on numbers)
Js.log(nan > nan == false) // inlined as >, correct behaviour
Js.log(nan->Obj.magic > nan->Obj.magic == true) // Canl_obj.greaterthan

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions