dlang.org icon indicating copy to clipboard operation
dlang.org copied to clipboard

Associative Array Documentation

Open dlangBugzillaToGithub opened this issue 12 years ago • 2 comments

Walter Bright (@WalterBright) reported this on 2013-11-12T15:31:09Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=11507

CC List

  • LightBender
  • Chuck Allison

Description

Chuck Allison writes:

It states:

When an AA indexing access appears on the left side of an assignment operator, it is specially handled for setting AA entry associated with the key.

string[int] aa;
string s;
s = aa[1];          // throws RangeError in runtime
aa[1] = "hello";    // handled for setting AA entry
s = aa[1];          // succeeds to lookup
assert(s == "hello");


If the assigned value type is equivalent with the AA element type:

    If the indexing key does not yet exist in AA, a new AA entry will be allocated, and it will be initialized with the assigned value.
    If the indexing key already exists in the AA, the setting runs normal assignment.


It does not explicitly state that a new entry may be default initialized, as in:

int[string] myaa;
++myaa[“foo”];   // 0+1 = 1

It might be nice to say so.

Also, I realize this is a matter of taste, but wouldn’t a short, high-level word-count example be more attractive than the example that is there? For example:

    string[] words = split(cast(string) read(filename));
    int[string] counts;
    foreach (word; words)
        ++counts[word];    // default initialization used here
    foreach (w; counts.keys.sort)
        writefln("%s: %d", w, counts[w]);

This code opens a file, tokenizes it, does the word mapping, and prints the result in sorted order all in 6 lines. I find this more compelling and easier to grok at a glance.

dlangBugzillaToGithub avatar Nov 12 '13 15:11 dlangBugzillaToGithub

bearophile_hugs commented on 2013-11-12T16:02:54Z

(In reply to comment #0)

>     string[] words = split(cast(string) read(filename));

Better to use UFCS.


>     foreach (w; counts.keys.sort)

Built-in sort is deprecated!!

dlangBugzillaToGithub avatar Nov 12 '13 16:11 dlangBugzillaToGithub

chuck commented on 2013-11-13T10:19:40Z

Is this what you had in mind?

    string[] words = (cast(string)(read(filename))).split();
    int[string] counts;
    foreach (word; words)
        ++counts[word];
    foreach (w; sort(counts.keys))
        writefln("%s: %d", w, counts[w]);

dlangBugzillaToGithub avatar Nov 13 '13 10:11 dlangBugzillaToGithub