The docs for the Pervasives.compare
function state that
compare x y
returns0
ifx
is equal toy
, a negative integer ifx
is less thany
, and a positive integer ifx
is greater thany
.
This suggests it can return any negative or positive integer, not just -1
or 1
, to represent greater- or lesser-ness. However, does this actually happen?
This would make writing code like
match String.compare key new_key with
| 1 -> Node (left, insert new_key right, key)
| -1 -> Node (insert new_key left, right, key)
| _ -> Node (left, right, key)
much more difficult (using when
, probably?).
I'm particularly interested in String.compare
. Having a look at its implementation, it just forwards to Pervasives.compare
, which in turn is implemented natively using external
. No idea what it does.
An answer by yourself shows that no other values can be returned in the current implementation. I would be very careful, though, to rely on that. As long as compare
is not documented as being three-valued, future versions of OCaml may change that behaviour.
[EDIT, answering a comment] In order to avoid clumsy case distinctions (as hinted in your original question), you can wrap compare
into a function that returns a three-values type like so:
type comparison = Less | Equal | More
let my_compare a b = match compare a b with
| 0 -> Equal
| c when c>0 -> More
| _ -> Less
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With