Stray thought: Mapping over tuple values

I just encountered a small thing that perhaps could be expressed even better in Swift at some point in the future. Perhaps it has to do with Variadic Generics or extending non-nominal types, but I am not 100% sure:

I have two values of type A that I would like to map using the same function f: (A) -> B.

I could of course do:

let b1 = f(a1)
let b2 = f(a2)

But I would like to be able to express this a bit more concisely (namely in a fashion where it is clear to the reader that the same transform is being applied to both values - and that this is by intent and a2 should never ever be transformed in another fashion than a1).

I could of course do:

let bs = [a1, a2].map(f)

This has the level of conciseness that I would like, but now I have to index into bs in order to retrieve the values - which is alright, but perhaps it could be better:

let (b1, b2) = (a1, a2).map(f)

So in short: being able to map a tuple of values of the same type A into a same sized tuple of transformed values of type B.

From my vague understanding about Variadic Generics and it's application to tuples, it could some day be possible to define a function like map on a tuple of any size with the same generic type for each value.

Am I understanding these concepts correctly - and do people think that something like this will in fact be possible at some point?

2 Likes

Another option would be (a variation on?) tuple splatting:

let (b1, b2) = [a1, a2].map(f)

Perl allows this (I forget the exact syntax) with lists:

my ($b1, $b2) = @a;
1 Like

Why should the tuple be of the same type A? Function f can be Generic :wink:

1 Like

You’re completely right - that could also be the case.
In another thread there was mention of a revision to the variadic generics pitch coming out in a few weeks. Should be nice to see if that could tackle this situation!
:blush: