Tuple poilerplate code

Paul Backus snarwin at gmail.com
Tue Sep 1 11:22:04 UTC 2020


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];

I like using the following snippet for this kind of thing:

     /// Pass the members of a tuple as arguments to a function
     template unpack(alias fun)
     {
         import std.typecons: isTuple;

         auto unpack(T)(T args)
             if (isTuple!T)
         {
             return fun(args.expand);
         }
     }

Usage looks like this:

     f(...).unpack!((firstPart, secondPart) {
         // use firstPart and secondPart in here
     });

It also works very well in range pipelines; for example,

     auto nums = [1, 2, 3];
     auto animals = ["lion", "tiger", "bear"];

     zip(nums, animals)
         .map!(unpack!((num, animal) => 
animal.repeat(num).joiner(" ")))
         .each!writeln;

...which prints the output:

     lion
     tiger tiger
     bear bear bear


More information about the Digitalmars-d-learn mailing list