Why doesn't Swift have vector operations that work on tuples?

(Amir Michail) #1

For example, (1, 2) + (3, 4) should yield (4, 6) and 2*(1, 2) should yield (2, 4).


They're kinda hard to write in a scalable way. For example, (1, 2) + (3, 4) would use a different function for + than (1, 2, 3) + (4, 5, 6), and a new function would need to exist for every tuple of a different number of items. There could be some compiler hackery that would make it workable though. I'm not sure.

(David Sweeris) #3

Yeah, "no variadic tuples" is probably part of it. Another part is that tuples can't conform to protocols, so it can be tricky to use them generically. You could define all the vector ops for (Double, Double, Double) and (Double, Double), etc, but you couldn't then use them in a function defined like func whatevs <T: VectorType> (_ :T) because they couldn't conform to VectorType.

(Amir Michail) #4

Why not include tuple operations for a few common cases in Foundation for now?

(Richard Wei) #5

It'd be easier to implement when we have

  • generic parameter packs,
  • variadic tuples,
  • parameterized extensions, and
  • protocol conformances for structural types
extension<...T> (T...) : AdditiveArithmetic where T... : AdditiveArithmetic {
  static func + (lhs: (T...), rhs: (T...)) -> (T...) {

(Steve Canon) #6

All the things that Richard said, but also Tuples are more a more general concept than Vectors.

Lots of things that people represent as tuples either shouldn’t have operators, or they should have different semantics:

  • the (high, low) result pair of a multipliedFullWidth result.
  • the (quotient, remainder) result of a division.
  • complex numbers represented as (real, imaginary).
  • basically any case where a tuple is not homogeneous: (name, age), etc.

Vectors are fundamentally a more restricted thing than Tuples, and you really don’t want to lift vector operations onto Tuples.