digitalmars.D.bugs - [Issue 11642] New: Handy object AA.setDefault function
- d-bugmail puremagic.com (49/49) Nov 29 2013 https://d.puremagic.com/issues/show_bug.cgi?id=11642
https://d.puremagic.com/issues/show_bug.cgi?id=11642 Summary: Handy object AA.setDefault function Product: D Version: D2 Platform: All OS/Version: All Status: NEW Severity: enhancement Priority: P2 Component: DMD AssignedTo: nobody puremagic.com ReportedBy: bearophile_hugs eml.cc 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. -- Configure issuemail: https://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------
Nov 29 2013