Inserting to associative array do not return a lvalue.
Bill Baxter
dnewsgroup at billbaxter.com
Tue Oct 16 12:26:33 PDT 2007
Steven Schveighoffer wrote:
> "Bill Baxter" wrote
>> BCS wrote:
>>> Reply to Yang,
>>>
>
> Technically, the extra lookup isn't very costly. Most likely you add keys
> rarely. To make the code more optimized, you would do something like:
>
> int *r = null;
> if(!(r = 1 in a))
> {
> a[1] = 0;
> r = 1 in a;
> }
> *r = 2;
> (*r)++;
>
> This allows you to avoid the extra lookup (actually extra 2 lookups) if the
> node already exists, which should be the more common case. If you analyze
> it in big-O notation, the extra-lookup factor is really only a constant, and
> so the complexity is the same.
>
> However, we already have properties on AA's that are built into the
> language. Would it not make sense to do this as a property? e.g.:
>
> int *r = a.setval(1, 2);
> (*r)++;
>
> Due to the way functions on arrays can be used as properties, you could even
> have:
>
> int *setval(int[int] arr, int key, int val)
> {
> int *r = key in arr;
> if(!r) // triple lookup only on first call to setval
> {
> arr[key] = val;
> r = key in arr;
> }
> else
> *r = val;
> return r;
> }
>
> This can be done without augmenting the language spec, although it still has
> the triple lookup cost on the first call which could be avoided if it was
> done in the language itself. I'm sure someone out there can templatize this
> :)
I'd also like to have Python's pop,popitem,get,setdefault, and update
functions built-in. Or at least defined in a std.something.
--bb
More information about the Digitalmars-d
mailing list