« 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 13 Jun 2009, at 1:09 am, Simon Strobl wrote:

>
> Hello,
>
> I have just been fiddling around with a predicate that did the right  
> thing
> only in the vast majority of cases. Eventually, I found out that my  
> problem
> was that in a sorting procedure, I sometimes compared integers to  
> floats. It
> would never have occurred to me that compare(>, 1, 1.0) is true.

Well, they *CAN'T* compare equal, because they are not the same term.
compare/3 is supposed to be total, so one of them has to be greater
than the other in the term order.

>
> Does this really have to be true?

Well, for one thing, the standard says so:

7.2 Term order
     If X and Y have different types: X term-precedes Y iff
     the type of X precedes the type of Y in the following order:
     variable precedes floating point precedes integer precedes
     atom precedes compound.

> Maybe there are good reasons why this should be so.

(1) compare/3 is supposed to be total.
(2) compare/3 is supposed to be consistent with arithmetic ordering
     for integers compared with integers and for floating point
     numbers compared with floating point numbers.
(3) compare(=, X, Y) may only succeed when X and Y are
     indistinguishable.
(4) 1 and 1.0 are not indistinguishable.  For example, it is
     possible to find an integer X such that X+1 > X but
     X+1.0 =:= X.
(5) From (3 and 4), compare(=, 1, 1.0) may not succeed.
(6) From (1 and 5), either compare(<, 1, 1.0) or compare(>, 1, 1.0).
(7) The choice between those two alternatives is fairly arbitrary,
     but it has to be consistent.  The standard chose float < integer.


> But then a word of warning in the manual entry of compare/3
> would be very useful.

Not a bad idea.   Just because something is standard and pretty
much necessary really doesn't mean it is obvious.

In the mean time, I suggest that mixing integers and floats in
a single sort is problematic in one way or another in most
dynamically typed languages.  For example, in one otherwise
sensible language, it is possible to find numbers X, Y, Z such
that X =:= Y and Y =:= Z but X < Z.


_______________________________________________
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