Proposal: property 'fetch' for AA
Oskar Linde
oskar.lindeREM at OVEgmail.com
Fri May 4 00:10:57 PDT 2007
eao197 skrev:
> Ruby's Hash has a handy method 'fetch'[1] which allows to extract value
> from Hash or, if value is missed, use some default value:
> If D's AA would have property 'fetch' it would allow to write:
>
> int[char] h;
> h[ 'a' ] = 1;
> auto a = h.fetch( 'a', 0 );
> auto b = h.fetch( 'b', 10 );
>
> instead of:
>
> V fetch(K,V)( V[K] h, K key, V default_value )
> {
> if( key in h )
> return h[key];
> return default_value;
> }
A slightly different version I've been using:
T get(T,U)(T[U] aa, U key) {
T* ptr = key in aa;
if (ptr)
return *ptr;
return T.init;
}
T get(T,U, int dummy = 1)(T[U] aa, U key, lazy T defaultValue) {
T* ptr = key in aa;
if (ptr)
return *ptr;
return defaultValue;
}
and
T getCached(T,U)(T[U] aa, U key, lazy T computedValue) {
T* ptr = key in aa;
if (ptr)
return *ptr;
T val = computedValue;
aa[key] = val;
return val;
}
The latter one could probly use a better name, but the idea is to
conveniently be able to use an AA as a cache for expensive computations.
/Oskar
More information about the Digitalmars-d
mailing list