AA default value?
Bill Baxter
dnewsgroup at billbaxter.com
Fri Jan 25 08:16:38 PST 2008
Janice Caron wrote:
> On 1/25/08, Janice Caron <caron800 at googlemail.com> wrote:
>> ((p = (key in aa)) is null) ? *p : defaultValue)
>
> Spot the deliberate (ahem) mistake! Hint - there's a missing
> exclamation mark somewhere. :-)
>
> Seriously, really I just want aa[key] to return some default value.
> Whether that's value.init, or some settable property within AAs, or if
> it could somehow be expressed at the call site - any or all of those
> options would be fine.
Oskar gave you a solution.
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;
}
Which looks exactly like a D translation of Python's get method for dicts.
Python also has setdefault, which does the same as get() but also sets
the value to the specified default if it didn't exist before. I'm not
wild about that name "setdefault" but anyway having the method in the
std lib is good.
T setdefault(T,U)(T[U] aa, U key) {
T* ptr = key in aa;
if (ptr)
return *ptr;
aa[key] = T.init;
return T.init;
}
T setdefault(T,U,int dummy=1)(T[U] aa, U key, lazy T defaultValue) {
T* ptr = key in aa;
if (ptr)
return *ptr;
aa[key] = defaultValue
return aa[key];
}
--bb
More information about the Digitalmars-d
mailing list