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

Dmitri Gribenko gribozavr at gmail.com
Mon Dec 7 14:01:09 CST 2015


On Mon, Dec 7, 2015 at 11:48 AM, Kevin Ballard via swift-evolution <
swift-evolution at swift.org> wrote:

> 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
> }
>

Looks like a good idea to me!  Also the <= and >= operators, right?

What concerns we with massive code generation is the code size of the core
swift library.  It would be definitely important to see how much code this
adds, depending on the number of tuple elements.

I personally don't see a point in going as high as 12 tuple elements.
About 4 or 5 makes sense to me.  Given that Swift does not have variadic
generics right now, these long tuples have to be defined by someone
manually.  If one is defining a tuple that is that long, I'd argue that
they should be using a custom struct instead.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/21c92d7f/attachment.html>


More information about the swift-evolution mailing list