[swift-users] Exceptional values in the Comparable protocol

Dave Abrahams dabrahams at apple.com
Mon Jul 10 16:23:05 CDT 2017


on Sun Jul 09 2017, Martin R <swift-users-AT-swift.org> wrote:

> The Comparable protocol requires that < and == impose a strict total
> order: exactly one of a==b, a<b, a>b must hold for all values a and b
> of a conforming type.
>
> But it is also noted that a conforming type may contain a subset of
> „exceptional values“ which do not take part in the strict total order
> (such as FloatingPoint.nan).
>
> What does that mean for functions taking comparable arguments, e.g.
>
>     func mySuperSort<T: Comparable>(a: inout [T]) { }
>
> Can the function implementation assume that all values passed to it
> take part in the strict total order? In other words: „exceptional
> values“ must not be passed to the function?

Yes

> Or must the function take that case into account and must not assume
> that exactly one of a==b, a<b,
> a>b holds for any arguments passed to it?

It need not, but it may do so as a matter of QOI (Quality Of
Implementation).  It is a good idea to make such a function work for NaN
if you can figure out what the semantics should be and it doesn't overly
impact the performance of other important use cases.

Hope this helps,

-- 
-Dave



More information about the swift-users mailing list