Challenge Tuples

Sergey kornburn at yandex.ru
Sat Apr 27 18:33:52 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);
> }
> ```
> 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!

For Python it is possible to use something like:
```python
t = (1,2,3,[1,3],5)
for e in t:
     a.append(e) if isinstance(e, int) else a.extend(e)
print(sum(a))
```



More information about the Digitalmars-d-learn mailing list