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

Haravikk swift-evolution at haravikk.me
Sun Apr 24 14:47:14 CDT 2016

> On 24 Apr 2016, at 17:41, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> Regarding how this affects sorting methods though, some people (myself included) like the simplicity of being able to do the following:
> 	myArray.sort(>)	// If array is of Comparable elements, just throw in the operator
> While for less-than you could just pass in the new operator instead, is there an easy way to flip the operator to achieve a similar result?
> What's wrong with reverse()?

Nothing in that specific case I suppose, but in similar cases that don’t return something that .reverse() can be used with it will be a bit more awkward to work with; in-place sorting would perhaps be a better example, as you can’t just expect everything the array is passed on to to call .reverse(), as they may not know what the order is supposed to be. This is where the full range of current comparison operators are useful. I considered that we could have two ordering operators such as <=< and >=> for ascending and descending respectively as drop-in replacements for < and >, but this wouldn’t help cases where <= and >= are used and I doubt we want yet more operators.

The enum could be given a raw type of Int with values of .Below (-1), .Same (0) and .Above (1), which would allow me to do: .sortInPlace({ $0 <=> $1 > 0 })
Though that feels a bit weird, like I should be testing against the actual enum cases, but doing so gets messy very quickly. Java uses an integer for sorting order, but then iirc their enum type came later so they might have used it if they’d had it, but their integer value has the added bonus that it can also optionally represent an estimate of how far two elements are displaced from one another.

On which note actually, should the .Below and .After cases include a stored value to give an optional estimate of displacement? This needn’t actually be used, and for some types won’t be accurate enough to be useful (in which case it should just be 1), but in some cases it can be useful to provide and use when documented properly.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160424/7c71987c/attachment.html>

More information about the swift-evolution mailing list