Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can compare return anything else than -1, 0 and 1?

The docs for the Pervasives.compare function state that

compare x y returns 0 if x is equal to y, a negative integer if x is less than y, and a positive integer if x is greater than y.

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.

like image 874
Bergi Avatar asked Dec 14 '16 08:12

Bergi


1 Answers

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
like image 88
kne Avatar answered Sep 30 '22 01:09

kne