[swift-evolution] [pitch] Comparison Reform

John McCall rjmccall at apple.com
Thu Apr 13 17:23:21 CDT 2017


> On Apr 13, 2017, at 4:17 PM, Ben Cohen via swift-evolution <swift-evolution at swift.org> wrote:
> ComparisonResult Conveniences
> 
> There are a few conveniences we could consider providing to make ComparisonResult more ergonomic to manipulate. Such as:
> 
> // A way to combine orderings
> func ComparisonResult.breakingTiesWith(_ order: () -> ComparisonResult) -> ComparisonResult
> 
> array.sort {
>   $0.x.compare($0.y)
>   .breakingTiesWith { $0.y.compare($1.y) }
>   == .orderedAscending 
> }

The really nice thing about compare being an operator is that you can very nicely combine it with an operator here and get a much more light-weight syntax for chained comparisons, e.g.:

struct MyPoint : Comparable {
  var x, y, z: Double
  func compare(_ other: MyPointer) -> ComparisonResult {
    return self.x <=> other.x || self.y <=> other.y || self.z <=> other.z
  }
}

as opposed to, I guess,
  return self.x.compare(other.x).breakingTiesWith { self.y.compare(other.y).breakingTiesWith { self.z.compare(other.z) } }

But this is mostly useful for defining custom comparisons, so perhaps it's not worth having to paint a bikeshed for <=> and whatever the combining operator is.

Also, in this example:
> // A way to combine orderings
> func ComparisonResult.breakingTiesWith(_ order: () -> ComparisonResult) -> ComparisonResult
> 
> array.sort {
>   $0.x.compare($0.y)
>   .breakingTiesWith { $0.y.compare($1.y) }
>   == .orderedAscending 
> }
Requiring this last "== .orderedAscending" seems like a tragic failure of ergonomics.  I understand that sorting doesn't actually require a tri-valued comparison, but is it really worth maintaining two currencies of comparison result over that?  Are there any types that can answer '<' substantially more efficiently than they can answer 'compare'?  And I assume this is related to why you've kept < in the protocol.

John.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170413/80227f54/attachment.html>


More information about the swift-evolution mailing list