Bug 11642 – Handy object AA.setDefault function

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
druntime
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-11-29T04:42:45Z
Last change time
2018-11-22T18:26:39Z
Assigned to
No Owner
Creator
bearophile_hugs

Comments

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
Four and a half years isn't that bad, is it? Sigh... https://dlang.org/spec/hash-map.html#inserting_if_not_present void main() { import std.stdio; char[int] aa; aa.require(10, 'X').writeln; aa.writeln; aa.require(20, 'Y').writeln; aa.writeln; } Output: X [10:'X'] Y [20:'Y', 10:'X'] Fixed by https://github.com/dlang/druntime/commit/0c92d13c7f8540bd91c3cce251d97ff39b84a486