Comment #0 by bearophile_hugs — 2013-11-29T04:42:45Z
I suggest to add to object.d another simple associative array function (similar to get()), with the semantics of the Python "setdefault" dict method:
From the Python docs:
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
A basic D implementation:
import std.traits;
TV1 setDefault(TK1, TV1, TK2, TV2)
(ref TV1[TK1] aa, TK2 key, TV2 defVal=TV2.init)
if (is(Unqual!TK1 == Unqual!TK2) && is(Unqual!TV1 == Unqual!TV2)) {
auto ptr = key in aa;
if (ptr == null) {
aa[key] = defVal;
return defVal;
} else
return *ptr;
}
void main() {
import std.stdio;
char[int] aa;
aa.setDefault(10, 'X').writeln;
aa.writeln;
aa.setDefault(20, 'Y').writeln;
aa.writeln;
}
Output:
X
[10:'X']
Y
[20:'Y', 10:'X']
At first sight this small function could look a bit strange, but it turns out to be quite handy to build associative arrays as you go inside an algorithm.
Comment #1 by andrej.mitrovich — 2014-05-04T10:57:55Z
Changing to a druntime ER. It should be implemented there to be efficient. I'll give a go at this soon.
Comment #2 by stanislav.blinov — 2018-11-22T18:26:39Z