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

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Feb 7 12:46:20 PST 2013


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.


More information about the Digitalmars-d-learn mailing list