Making associatvie array from array of pairs

Philippe Sigaud philippe.sigaud at gmail.com
Tue Dec 24 04:33:04 PST 2013


On Tue, Dec 24, 2013 at 1:12 PM, bearophile <bearophileHUGS at lycos.com> wrote:
> Philippe Sigaud:
>
>
>>     auto a = [["1","0000FF"], ["2", "00FF00"]];
>>     import std.algorithm: reduce;
>>    string[string] b;
>>     b = reduce!((aa, pair) { aa[pair[0]] = pair[1]; return aa;})(b,a);
>>     writeln(b);
>
>
> While this code seems correct (and I think it's kind of common in Scala)

I don't know Scala much (I find the code it makes me write is far too
'heavy', if I may say so).
Haskell would be more the origin of my using reduce :-)

> consider it an obfuscation to avoid. A normal foreach loop is much more
> readable and should be preferred for this. Functional-style programming is
> not always the best.

I don't know. I really consider `reduce` a nice way to collapse a
structure down to a value. I find it in many different places. Sure,
map and filter are more usual, but reduce is not far behind.

Anyway... Here with a foreach loop:

    auto a = [["1","0000FF"], ["2", "00FF00"]];
    string[string] b;

    foreach(pair; a)
        b[pair[0]] = pair[1];


More information about the Digitalmars-d-learn mailing list