Challenge Tuples

Andrey Zherikov andrey.zherikov at gmail.com
Wed May 1 14:15:19 UTC 2024


On Friday, 26 April 2024 at 13:25:34 UTC, Salih Dincer wrote:
> You have a 5-item data tuples as Tuple(1, 2, 3, [1, 3], 5) and 
> implement the sum (total = 15) with the least codes using the 
> sum() function of the language you are coding...
>
>
> Let's start with D:
>
> ```d
> import std.typecons : tuple;
> import std.algorithm : sum;
>
> void main()
> {
>   auto t = tuple(1, 2, 3, [1, 3], 5);
>
>   int[] arr;
>   t.each!(e => arr ~= e);
>   assert(arr.sum == 15);
> }
> ```
>
> and bonus:
>
> ```d
> import std.typecons : tuple;
> import std.stdio : writeln;
> void main()
> {
>   auto t = tuple(1, 2, 3, [1, 3], 5);
>   auto results = [0];
>
>   foreach (data; t)
>   {
>     static
>     if (is(typeof(data) == int[]))
>     {
>       int sum;
>       foreach (d; data)
>       {
>         sum += d;
>       }
>       results ~= sum;
>     }
>     else
>     {
>       results ~= data;
>     }
>   }
>   results.writeln; // [0, 1, 2, 3, 4, 5]
> ```
>
> I bet you won't be able to do it this easily with other 
> languages!  Note: I tried with C# and Python and it didn't work!
>
> SDB at 79


Shorter and without allocations:
```d
import std.typecons : tuple;
import std.algorithm : sum, each;

auto sum(int i) => i;

void main()
{
   auto t = tuple(1, 2, 3, [1, 3], 5);

   int res=0;
   t.each!(e => res += sum(e));
   assert(res == 15);
}
```



More information about the Digitalmars-d-learn mailing list