Comparable and FloatingPoint types

It’s not so hard to imagine a context where the developer assumes > is consistent with sorted():

// Iterating over all nums ≤ max in sorted order:
for n in nums.sorted() {  // Sorting using Comparable behavior, NaNs come first
    guard n < max else {  // Wrongly assuming > is consistent with sorted()...
        return            // ...we ignore all elements if nums contains a NaN
    }
    ...
}

Granted, this code is also broken under the current misbehavior of sorted()! But this proposed solution feels like a game of illogic whack-a-mole.

I’ll also grant there’s not an obvious better solution.

The strictly correct one would be not to let Float implement Comparable at all, and instead have a separate OrderedFloat wrapper. The attendant conversion nuisance and source impact is probably a deal-killer for that.

I’m also tempted to propose an IEEE-compliant &> for Float, in the spirit of &+ for Int. I can see that the existing source impact of that is probably not acceptable. It is worth considering, however, Swift’s precedent here: when translating code from other languages, one does have to consider whether to use + or &+ — and the operator that gives the more familiar behavior is the weird-looking one, not the default +.

5 Likes