# [swift-evolution] [Proposal] Formalized Ordering, take 2

David Sweeris davesweeris at mac.com
Mon Jul 25 16:02:43 CDT 2016

```> On Jul 25, 2016, at 2:28 PM, Pyry Jahkola via swift-evolution <swift-evolution at swift.org> wrote:
>
>
>> On 25 Jul 2016, at 21:23, Nevin Brackett-Rozinsky <nevin.brackettrozinsky at gmail.com <mailto:nevin.brackettrozinsky at gmail.com>> wrote:
>>
>> My one question is, will I be able to write `someCollection.sort(.ascending)` and get the expected result? (This could be an additive future direction.)
>
>
> To sort to ascending order, you'd still just call `.sort()` with no arguments.
>
> To limit the scope of this proposal somewhat, I moved the introduction of new sorting functions into the Future directions section. All of those changes are additive in a way or another:
>
> 1. The default .sort() function would use `<=>` instead of `<`.
>
> (a) On the one hand, we'd get improved performance in cases like Array<String>.sort() where doing another `<` comparison would be more costly.
> (b) On the other hand, we'd get well-defined behaviour when sorting Double arrays containing NaNs, because all non-NaN values would be sorted into one contiguous subrange of the result.

Two quick questions…
1) What about adding an `isInvalid` case? That way types (such as Double/Float) which have “unordered” values can check for an invalid comparison.
2) What about making `Ordering` a tuple instead of an enum? “typealias Ordering = (isLessThan: Bool, isEqual: Bool, isGreaterThan: Bool, isInvalid: Bool)”? It’d take up more space on the stack, but I think this:
func < (lhs: Int, rhs: Int) -> Bool {
return (lhs <=> rhs).isLessThan
}
or even this:
func < (lhs: Int, rhs: Int) -> Bool {
let ord =  (lhs <=> rhs).isLessThan
return ord.isLessThan && !ord.isInvalid
}

would execute faster than this:
func < (lhs: Int, rhs: Int) -> Bool {
switch (lhs <=> rhs) {
case lessThan: return true
default: return false
}

because there wouldn’t be any branching beyond what’s necessary to do the actual comparison.

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160725/57e4b4fc/attachment.html>
```