On 4/17/18 12:18 PM, Nick Treleaven wrote:
On Sunday, 15 April 2018 at 22:52:47 UTC, Giles Bathgate wrote:
The function provides a means to get a value corresponding to the key,
but if the value doesn't exist it will evaluate the lazy argument to
create a new value, add this to the associative array and then return it.
auto p = lookup.getOrAdd("giles", new Person);
Thanks for making this pull, I've thought about solving this before. I
think the function needs to provide a way to tell if the value was
already present.
Not as straightforward, but it can be done:
bool inserted = false;
auto p = aa.getOrAdd("key", {inserted = true; return new Person; });
Note that most of the time, the only reason you need to know it's new is
to initialize it. But the lazy parameter takes care of that for you.
I also think it's more ergonomic not to have to use a
lazy argument, and probably more efficient, so I had in mind:
Value* slot(AA aa, K key, scope bool* inserted = null);
I like the name slot. I'm less enthused about the extra machinery needed
for initializing the value.
Why do you think it's less efficient to use a lazy parameter?
This pattern needs a pointer to be returned, instead of using `ref`.
Note that `&inserted` is valid in @safe code, but only with -dip1000. I
called the function `slot` because it always returns the address of the
slot which the value is stored in.
Returning ref makes more sense to me -- you are never going to return null.
-Steve