D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 9491 - [AA] allow for insert/return pointer to existing value if present on assoc array
Summary: [AA] allow for insert/return pointer to existing value if present on assoc array
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: druntime (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-02-09 11:18 UTC by Daniel Davidson
Modified: 2018-11-23 11:35 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Daniel Davidson 2013-02-09 11:18:08 UTC
By providing something like:

auto ptrToValue = hash.insertDefaultOrFind(key, init)
*ptrToValue += additional;

client code can perform an <insert if not present/lookup> combined so that on the
case of a nonexistent key, 1 toHash/lookup can be done instead of 3.

The best recap of what is needed is in this thread:
http://forum.dlang.org/post/mailman.1081.1360269373.22503.digitalmars-d-learn@puremagic.com
Comment 1 w0rp 2014-04-09 07:54:06 UTC
I know exactly the kind of thing you are talking about. What you want is a setDefault function with an overload. These functions should have these signatures.

ref V1 setDefault(K, V1, V2)(ref V1[K] map, K key, lazy V2 value) if (is(V2 : V1));
ref V setDefault(K, V)(ref V[K] map, K key);

Where the second overload is equivalent to setDefault(map, key, V1.init) above. This is basically 'setdefault' from Python, only better because the value is lazy.

I have written a higher level implementation of this myself before, but I believe a druntime implementation could do better by computing a hash for K once, like you say.
Comment 2 Stanislav Blinov 2018-11-23 11:35:22 UTC
Since https://github.com/dlang/druntime/commit/0c92d13c7f8540bd91c3cce251d97ff39b84a486 (present in 2.082) there is now a require() function that does exactly that.