[swift-evolution] [Idea] Bringing the partial/total ordering distinction into Comparable

Chris Lattner clattner at apple.com
Sun Apr 24 17:03:14 CDT 2016


> On Apr 24, 2016, at 2:51 PM, Brent Royal-Gordon <brent at brentdax.com> wrote:
> 
>> However, I don’t understand how that would help for floating point NaN behavior.  Wouldn’t you have to add a fourth member to the enum (“unordered’) that all clients would have to handle?  An approach like that could make sense.
> 
> The point is precisely that there *isn't* an `unordered` case. The spaceship operator *must* order all values; that makes it suitable for operations like `sort()` and `max()` which assume there is a total order over all values they encounter. Meanwhile, the traditional comparison operators like `<` and `==` are given flexibility to implement looser semantics like those seen in `FloatingPoint`.
> 
> On the other hand, just because there is *an* order doesn't mean it'll be a *sensible* order. In particular, if `min()` and `max()` are based on an ordering which includes NaNs, then in some circumstances at least one of them will favor a NaN over a normal value. It might be that the total order is not actually a good match for `min()` and `max()`, and they should instead use the partial order and ignore unordered elements.
> 
> (Of course, that again raises the question of whether it is an element or a *pair* of elements which is unordered.)
> 
> Perhaps think of it this way: `<=>` is an *ordering* operator; the others are *comparison* operators. The difference is that, even if two elements cannot be compared, they can still have a consistent order.

Ah, I see what you’re saying.  I don’t think that I would be in favor of this sort of approach: the only model we have to motivate this is floating point, and the use cases (e.g. sorting an array with nans in it) are uncommon, and it isn’t clear where nans should sort (beginning, middle, or end?).

For specific call sites that do have a specific handling in mind, they can pass in a closure predicate that does the specific comparison necessary for that call.

-Chris


More information about the swift-evolution mailing list