www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Challenge Tuples

reply Salih Dincer <salihdb hotmail.com> writes:
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 


SDB 79
Apr 26
next sibling parent matheus <matheus gmail.com> writes:
On Friday, 26 April 2024 at 13:25:34 UTC, Salih Dincer wrote:
 ...
Very nice, for your first example I need to think a bit because version. For the bonus part: private static void Main(string[] args){ var a = (1,2,3,(1,3),5); var t = a as ITuple; var xx = new List<string>(); for(var i=0;i<t.Length;++i){ if(t[i].GetType() == typeof(System.ValueTuple<Int32,Int32>)){ var t2 = (t[i] as ITuple); var s = 0; for(var j=0;j<t2.Length;++j){ s+=(int)t2[j]; } xx.Add(s.ToString()); }else{ xx.Add(t[i].ToString()); } } Console.WriteLine(string.Join(",",xx)); return; } the D version. Matheus.
Apr 26
prev sibling next sibling parent Andy Valencia <dont spam.me> writes:
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...
My Python solution (function named dosum to avoid collision w. Python primitive): def dosum(itm): if isinstance(itm, (int, float)): return itm return sum( dosum(_i) for _i in itm ); print dosum( [1, 2, 3, [1, 3], 5] )
Apr 26
prev sibling next sibling parent reply Basile B. <b2.temp gmx.com> writes:
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:
Here's [STYX](https://gitlab.com/styx-lang/styx) solution: function sum[T,U](U u): u32 { var T result; foreach const e in u do if echo(is, e, T) do result += e; else do result += sum![T](e); return result; } function main(): s32 { assert((1, 2, 3, [1, 3], 5).sum![u32]() == 15); return 0; } A few notes: - tuples are first class citizen - `foreach` over tuple is like in D, i.e unrolling - `echo` is like D `__traits` - _Implicit Generic Application_ of `U` (that's like D's IFTI) makes the task easy
Apr 27
parent reply Nick Treleaven <nick geany.org> writes:
On Saturday, 27 April 2024 at 11:55:58 UTC, Basile B. wrote:
 Here's [STYX](https://gitlab.com/styx-lang/styx) solution:


     function sum[T,U](U u): u32
I think you meant `: T`.
     {
         var T result;
         foreach const e in u do
             if echo(is, e, T) do
                 result += e;
             else do
                 result += sum![T](e);
         return result;
     }

     function main(): s32
     {
         assert((1, 2, 3, [1, 3], 5).sum![u32]() == 15);
         return 0;
     }
Mostly equivalent D: ```d R sum(R = long, T)(T v) { R r; foreach (e; v) { static if (is(typeof(e) == int)) r += e; else r += sum!R(e); } return r; } void main() { import std; assert(tuple(1, 2, 3, [1, 3], 5).sum == 15); } ```
Apr 27
parent reply Nick Treleaven <nick geany.org> writes:
On Saturday, 27 April 2024 at 15:32:40 UTC, Nick Treleaven wrote:
 On Saturday, 27 April 2024 at 11:55:58 UTC, Basile B. wrote:
         foreach const e in u do
             if echo(is, e, T) do
                 result += e;
         static if (is(typeof(e) == int))
             r += e;
Actually I would write that: ```d R r; foreach (e; v) { static if (is(typeof(e) : R)) ```
Apr 27
parent Salih Dincer <salihdb hotmail.com> writes:
On Saturday, 27 April 2024 at 15:36:40 UTC, Nick Treleaven wrote:
 On Saturday, 27 April 2024 at 15:32:40 UTC, Nick Treleaven 
 wrote:
 On Saturday, 27 April 2024 at 11:55:58 UTC, Basile B. wrote:
         foreach const e in u do
             if echo(is, e, T) do
                 result += e;
         static if (is(typeof(e) == int))
             r += e;
Actually I would write that: ```d R r; foreach (e; v) { static if (is(typeof(e) : R)) ```
I like the new sum() function, great Nick! Moreover, it also works with an ordinary range: ```d enum limit = 100; // sum = 5050  iota(limit + 1).sum.writeln; ``` Moreover, it was implemented without defining IEnumerator. Well done Matheus! SDB 79
Apr 27
prev sibling next sibling parent Sergey <kornburn yandex.ru> writes:
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 

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)) ```
Apr 27
prev sibling next sibling parent Julian Fondren <julian.fondren gmail.com> writes:
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...
Nim: ```nim import std/[math, typetraits, macros] macro unrollRange(low, high: static int; name, body: untyped) = result = newStmtList() for i in low ..< high: result.add(newBlockStmt(newStmtList( newConstStmt(name, newLit i), copy body ))) let t = (1, 2, 3, [1, 3], 5) var arr: seq[int] unrollRange(0, t.tupleLen, i): arr.add t[i] doAssert arr.sum == 15 ``` vs. D 1. there's no `each` on tuples 2. there's no static for loop, so a macro is needed for the tuple indices 3. `add` is making use of the same overload as D's `~=`
Apr 27
prev sibling parent reply Andrey Zherikov <andrey.zherikov gmail.com> writes:
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 


 SDB 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); } ```
May 01
parent reply Salih Dincer <salihdb hotmail.com> writes:
On Wednesday, 1 May 2024 at 14:15:19 UTC, Andrey Zherikov wrote:
 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);
 }
 ```
Super! In summary, D is clearly ahead of the tuple. Especially with its features similar to AliasSeq, I think it is unrivaled. Wouldn't it be great if there was a feature that worked at runtime... SDB 79
May 02
parent NotYouAgain <NotYouAgain gmail.com> writes:
On Friday, 3 May 2024 at 05:11:28 UTC, Salih Dincer wrote:
 ..
 Wouldn't it be great if there was a feature that worked at 
 runtime...

 SDB 79
module m; safe: private: import std; void main() { auto myTuple = tuple(1, 2, 3, [1, 3], 5); int[] arrToSum; foreach(int i, val; myTuple.expand) { if(typeof(val).stringof == "int[]") { foreach(v; myTuple.expand[i..i+1]) arrToSum ~= v; } else { arrToSum ~= val; } } writefln("The total value of the tuples is: %s", arrToSum.sum); // 15 }
May 03