On Tuesday, 1 September 2020 at 02:08:54 UTC, JG wrote:
Is there anyway to remove the boilerplate code of dealing with
tuples:
I find myself having to write things like this fairly often
auto someRandomName = f(...); //where f returns a tuple with
two parts
auto firstPart = someRandomName[0];
auto secondPart = someRandomName[1];
Is to possible to write something so that the above is
essentially equivalent to:
assignTuple!(firstPart,secondPart) = f(...);
The closest I can produce is using a template mixin so that I
would have to write:
mixin AssignTuple!(()=>f(...),"firstPart","secondPart");
When you know the types, this works:
import std.typecons : tuple;
import std.meta : AliasSeq;
int firstPart;
string secondPart;
AliasSeq!(firstPart, secondPart) = tuple(1, "foo");
assert(firstPart == 1);
assert(secondPart == "foo");
I know Timon Gehr worked on a DIP for improved tuples, which I
think would include the syntax `auto (firstPart, secondPart) =
tuple(1, "foo");`, but I don't know what's happened to that idea
lately.
I also feel it's worth pointing out that Paul Backus' code looks
elegant when used outside a map as well:
tuple(1, "foo").unpack!((i, s) {
writeln("i (", typeof(i).stringof, "): ", i,
", s (", typeof(s).stringof, "): ", s);
});
Will print:
i (int): 1, s (string): foo
--
Simen