Problem with AAs and ?:

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Mar 8 08:27:27 PST 2008


"bearophile" <bearophileHUGS at lycos.com> wrote in message 
news:fqu9np$27ic$1 at digitalmars.com...
> Can someone explain me where such difference comes from?
> Is this a bug?
>
> import std.stdio: writefln;
>
> void main() {
>    string[] words = ["how", "are", "you", "are"];
>
>    int[string] aa1;
>    foreach (w; words)
>        aa1[w] = ((w in aa1) ? (aa1[w] + 1) : 2);
>    writefln(aa1); // Prints: [how:1,you:1,are:2]
>
>    int[string] aa2;
>    foreach (w; words)
>        if (w in aa2)
>            aa2[w]++;
>        else
>            aa2[w] = 2;
>    writefln(aa2); // Prints: [how:2,you:2,are:3]
> }

This is odd.  Change the body of the first loop to:

auto val = (w in aa1) ? (aa1[w] + 1) : 2;
aa1[w] = val;

And they both output the same thing (2, 2, 3).

Sorry, breakfast time, I'll look at it a bit more afterwards ;) 




More information about the Digitalmars-d-learn mailing list