Trying to implement some random function I encountered this:

    uint randFunc(uint x)
    {
        static uint[uint] vals;
        if (auto r = x in vals) return *r;
        return vals[x] = uniform!uint();
    }

I have to lookup x twice and it seems that there is no way around it. Can't I tell the AA to set a value for a given key if it doesn't already have one
 (1) with only one lookup, and
 (2) in a safe way?
For the semantics, that should behave like this:

V set(K, V)(ref const(V)[const(K)] aa, auto ref const(K) key, lazy const(V) value)
    {
        if (auto valPtr = key in aa) return *valPtr;
        // cast away const as initialization is okay:
        return (cast() aa[key]) = value();
    }

The function is dual to AA's get.

It would make it possible for an AA with const value type to have values added which is perfectly fine for arrays. All I have seen so far, one cannot safely add values to them as initialization and assignment cannot be distinguished.

Reply via email to