Convert array of tuples into array of arrays.

Salih Dincer salihdb at hotmail.com
Thu Sep 1 07:28:16 UTC 2022


On Wednesday, 31 August 2022 at 17:26:56 UTC, Ali Çehreli wrote:
> [...] You can make an array of arrays from those with the 
> following syntax:
>
>   auto arrayOfArrays = [ keys, values ];
>
> Then I wrote a more general program after this first one:

I really like the generic methods. Because we can use enums for 
field names;  e.g:

```d
import std;

void main()
{
   enum {
     key = "productCode",
     val = "priceDolar"
   }

   auto makeTestTuple(int i)
   {
     return tuple!(key, val)((i * 2).to!string,
                    (double(i) / 10).to!string);
   }

   auto memberTuple(string member, T)(T tuples)
   {
     return mixin("tuples." ~ member);
   }

   auto tuples = 1.iota(10)
                  .map!makeTestTuple
                  .array;

   string[string] myList;

   foreach(t; tuples)
   {
       const keys = memberTuple!key(t);
     myList[keys] = memberTuple!val(t);
     keys.writeln(": ", myList[keys]);
   }
} /*
2: 0.1
4: 0.2
6: 0.3
8: 0.4
10: 0.5
12: 0.6
14: 0.7
16: 0.8
18: 0.9
*/
```

SDB at 79


More information about the Digitalmars-d-learn mailing list