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

Jonathan M Davis jmdavisProg at gmx.com
Thu Feb 7 13:36:03 PST 2013


On Thursday, February 07, 2013 21:46:20 Andrej Mitrovic wrote:
> On 2/7/13, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > I don't think that such a function exists
> > though.
> 
> UFCS would do it:
> 
> import std.traits;
> 
> auto ref set(Hash, Key, Val)(Hash hash, Key key, Val val)
> if (isAssociativeArray!Hash &&
> is(Key : KeyType!Hash) &&
> is(Val : ValueType!Hash))
> {
> if (auto res = key in hash)
> {
> return res;
> }
> else
> {
> hash[key] = val;
> return key in hash;
> }
> }
> ...
> 
> auto exists = _dataMap.set(k, init);
> 
> Note the use of "is(Val : ValueType!Hash)" which checks if Val can be
> implicitly converted to the value type, it's to allow e.g. assigning
> integrals to double.

I'd probably just make it return Val*. I don't know what you gain by making it 
return auto ref.

But regardless, your function is just doing the same thing that the OP's code 
is doing except that it's encapsulating it nicely. So, it improves upon the 
OP's code but doesn't solve the primary complaint about efficiency. It should be 
possible for the AA to implement set so that it doesn't require more than one 
lookup, whereas this does up to three.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list