Search for, o/w create element for AA

Q. Schroll via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 19 08:19:19 PDT 2017


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.


More information about the Digitalmars-d-learn mailing list