Why not allow elementwise operations on tuples?
Sergei Nosov
sergei.nosov at gmail.com
Fri Jan 13 14:22:34 UTC 2023
Hey, everyone!
I was wondering if there's a strong reason behind not
implementing elementwise operations on tuples?
Say, I've decided to store 2d points in a `Tuple!(int, int)`. It
would be convenient to just write `a + b` to yield another
`Tuple!(int, int)`.
I can resort to using `int []` arrays and write elementwise
operations as `c[] = a[] + b[]` which is almost fine - but it
uses dynamic allocation and forces the user to create an explicit
destination variable.
It seems a bit awkward given that it's fairly straightforward to
write smth as
```
T opBinary(string op, T)(T lhs, T rhs)
if (isTuple!T)
{
T result;
static foreach (i; 0 .. T.Types.length)
{
mixin("result.field[i] =
lhs.field[i]"~op~"rhs.field[i];");
}
return result;
}
```
You only need to turn it into a member function to make it work.
You can even make it more general and allow such operations for
different, but compatible tuple types (there's a function
`areCompatibleTuples` to check for such compatibility). Yet,
there's only a specialization for tuple concatenation of
`opBinary` (and an implementation of `opCmp` and `opAssign`).
So, to repeat the question - is this a deliberate decision to not
implement the default elementwise operation?
More information about the Digitalmars-d-learn
mailing list