[swift-evolution] Proposal: Implement == and < for tuples where possible, up to some high arity

Kevin Ballard kevin at sb.org
Mon Dec 7 13:48:35 CST 2015


I'd really like to see tuples support comparison operators when
possible. Eventually they should even conform to the
Equatable/Comparable protocols, but that requires tuples being able to
conform to protocols at all to begin with.

In the absence of some sort of variadic type parameters, we'd only be
able to support the comparison operators on tuples up to some predefined
arity. There's precedent in Rust and Haskell for this. Rust defines
these operations up to arity 12, Haskell defines them up to arity 15.

Behavior of == should be obvious. Behavior of the ordered comparison
operators would work like comparison of strings, where the first element
is compared, and if equal, the second element is compared, etc.

This would be implemented using some .gyb code that generates
declarations that look something like

func == <A: Equatable, B: Equatable, C: Equatable>(lhs: (A, B, C), rhs:
(A, B, C)) -> Bool {    return lhs.0 == rhs.0 && lhs.1 == rhs.1 && lhs.2
== rhs.2 }

func < <A: Comparable, B: Comparable, C: Comparable>(lhs: (A, B, C),
rhs: (A, B, C)) -> Bool {    if lhs.0 != rhs.0 { return lhs.0 < rhs.0 }
if lhs.1 != rhs.1 { return lhs.1 < rhs.1 }    return lhs.2 < rhs.2 }

func > <A: Comparable, B: Comparable, C: Comparable>(lhs: (A, B, C),
rhs: (A, B, C)) -> Bool {    if lhs.0 != rhs.0 { return lhs.0 > rhs.0 }
if lhs.1 != rhs.1 { return lhs.1 > rhs.1 }    return lhs.2 > rhs.2 }

If tuples ever gain the ability to conform to protocols (which I think
they should), and when types gain the ability to conditionally conform
to protocols, these declarations would be adjusted to declare the tuples
as conforming to Equatable and Comparable. This would be a backwards-
compatible change.

Similarly if Swift ever gains some form of variadic type parameters,
thus allowing for declaring behavior of arbitrary-sized tuples, then
this can be adjusted to use that feature and it should still be backwards-
compatible.

-Kevin Ballard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/caceb457/attachment.html>


More information about the swift-evolution mailing list