« Return to Thread: strange behaviour of compare/3

Re: strange behaviour of compare/3

by Richard O'Keefe :: Rate this Message:

Reply to Author | View in Thread


On 14 Jun 2009, at 4:08 am, Ulrich Neumerkel wrote:

> Simon Strobl writes:
>>                                                                         It
>> would never have occurred to me that compare(>, 1, 1.0) is true.
>
>> Does this really have to be true? Maybe there are good reasons why  
>> this
>> should be so. But then a word of warning in the manual entry of  
>> compare/3
>> would be very useful.
>
> compare/3 is a compact way to get the functionality of @< == etc.
> ISO Term order (13211-1:7.2) is a total ordering of all kinds of
> terms, including variables.  Even X and 3.0 compare - i.e. there is no
> instantiation error in X @< 3.0 but there is one in X < 3.0.
>
> The ordering is: variables, floats, integers, atoms, compounds.
>
> In any case: This kind of ordering is probably not the one you want,
> if you expect compare(=, 1, 1.0) to be true.
>
> You probably would like to have some numcompare/3 defined with =:= and
> <, yielding an instantation error for numcompare(R, 1, X).\

Remember above all that if you are sorting, you want your
comparison predicate to satisfy these laws:
     for all X, Y that might appear in your list,
(a) compare(R, X, Y) will succeed (where R is a fresh variable)
(b) it will bind R to one of =, <, >
(c) R will be = if and only if X == Y
(d) compare(<, X, Y) <=> compare(>, X, Y)
     for all X, Y, Z that might appear in your list,
(e) compare(<, X, Y) and compare(<, Y, Z) => compare(<, X, Z)

If you mix integers and floats in the same sequence it is
astonishingly tricky.  In fact it's astonishingly tricky to
deal with floating point numbers anyway.  Recall that for
IEEE floating point numbers, there are numbers Z, W such that
        X is -Z => X =:= Z but not X == Z   (±0)
        W == W but not W =:= W              (±NaN)
A programming language *cannot* be consistent with the IEEE
floating point standards AND provide a total order on the
floats under the usual symbols.  Historically, that's not the
reason that the term ordering predicates are distinct from the
numeric ordering ones, but it's a lucky accident that they were,
because otherwise we'd have had to break *something*.

Before defining your own num_compare/3 that mixes integers and
floats, or even just floats, make *very* sure that you know
what you are doing.

_______________________________________________
SWI-Prolog mailing list
SWI-Prolog@...
https://mailbox.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog

 « Return to Thread: strange behaviour of compare/3