May 03

On Wednesday, 1 May 2024 at 14:15:19 UTC, Andrey Zherikov wrote:

>

Shorter and without allocations:

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 03
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
}

1 2
Next ›   Last »