best idiom for insert if not present; else use value in assoc array

Ary Borenszweig ary at esperanto.org.ar
Fri Feb 8 16:09:25 PST 2013


On 2/7/13 5:20 PM, Dan wrote:
> For an associative array, what is the best idiom that allows for
> checking if a key exists in the AA. If it does do something with the
> value, if not initialize the value and then do something with it.
>
> In this code: http://dpaste.dzfl.pl/daab318f
>
> How would this piece be improved? It looks like it would have to perform
> the hash and do a find 3 times:
>
>      auto exists = (k in _dataMap);
>      if(!exists) {
>        _dataMap[k] = init;
>        exists = (k in _dataMap);
>      }
>      ... use *exists
>
> At a higher level and assuming the general goal of this basic struct is
> clear, any other suggestions welcome.
>
> Also, an FYI to dpaste maintainer that the compiler service has been
> unavailable for a while.
>
> Thanks
> Dan
>

In Ruby you can do this:

h = Hash.new(0) # 0 is the default value if the key is not present

Now you can do:

h[0] += 3 #=> {0 => 3}
h[1] = 4  #=> {0 => 3, 1 => 4}

You can even initialize a hash with a lambda that computes the initial 
value based on a key:

h = Hash.new { |hash, key| hash[key] = key * 2 }

h[10] #=> 20

I guess in D you would create a struct that wraps an associative array 
and adds that logic.


More information about the Digitalmars-d-learn mailing list