This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

Pervasives.compare output type
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2005-03-29 (08:15) From: Oliver Bandel Subject: Re: [Caml-list] Pervasives.compare output type
```On Thu, Mar 24, 2005 at 07:47:23PM +0100, Alex Baretta wrote:
> Pervasives.compare currently returns an int. Intuitively it would be
> more appropriate for it to return a union type such as the following.
>
> type comparison_result = Less | Equals | Greater
>
> What are the reasons behind the present design choice?

Maybe it was a historical reason?

Didn't comparison functions (in C and many other languages too)
throw out an integer value?!

Having -1 for smaller (less(er?)) and +1 for bigger (greater)
and 0 for equal makes sense at least for integers.

let sgn a = match a with
_ when a > 0 -> 1
| _ when a < 0 -> -1
| _ -> 0

let compare int_1 int_2 = sgn(int_1 - int_2)

As compare normally is a computation that is used to compare
integers, but can be more generalized to comparing strings
and so on, and maybe because comparing (integers) is derived
from the area of mathematics, this historic offset may be
the reason for that return value.
E.g. comparing strings can be (seems to be) implemented as
comparing the integer-values of the characters (index)
in the ASCII charset.
So, again: that's mathematics of comparing integers.

So all in all, there may be these reasons here:

- derived from mathematics on integers (and easy implementation to
use the sub of two integers for getting the result, which one
is greater than the other one, then using the sign of that subtraction)

- resulting value is like in other programming languages an integer value

Nevertheless it could be done with an output type like you gave above.

But you can wrap it, if you want:

type comparison_result = Less | Equals | Greater
let compare_symbres a b = match (compare a b) with
|  1 -> Greater
| -1 -> Less
|  _ -> Equals

Ciao,
Oliver

```