Challenge Tuples

Salih Dincer salihdb at hotmail.com
Fri Apr 26 13:25:34 UTC 2024


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


More information about the Digitalmars-d-learn mailing list