Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

associative arrays need 2 lookups to remove and extract, should be 1 #17204

Open
dlangBugzillaToGithub opened this issue Feb 27, 2023 · 0 comments
Labels
Druntime:AA Specific to Associative Arrays Druntime Specific to druntime P4 Severity:blocker Severity:Enhancement

Comments

@dlangBugzillaToGithub
Copy link

Bolpat reported this on 2023-02-27T17:02:22Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=23748

CC List

  • Bolpat

Description

There is no way to remove a key–value pair and extract the value with one lookup. One has to make one lookup to get the value (if any), and another to remove the pair.

Currently, the `remove` function returns a `bool` value indicating via `true` that a key–value pair with the passed `key` was present, and `false` when it was not.

This could be improved by instead returning a pointer to the value if they pair existed, and `null` otherwise, i.e. exactly what `in` does, but additionally removing the value.

With this enhancement, extract–remove is a trivial one-liner.
Compare this:
```d
Value* v = key in aa;
aa.remove(key);
if (v != null)
{
    // handle the value
    // *v is valid even after removal.
}
```
with this:
```d
if (Value* v = aa.remove(key))
{
    // handle the value
}
```

There should be minimal breakage because most current uses of `remove` will ignore its result anyways, and if not, the returned pointer converts to `true` implicitly if it is not `null` and `null` to `false` in contexts where a `bool` is required.

If that breakage cannot be tolerated or the new implementation is deemed considerably more expensive than current `remove`, I suggest a new function by the name `removeAndExtract` or (cf. Scott Mayers: `takeOut`).
@thewilsonator thewilsonator added Severity:Enhancement Severity:blocker Druntime Specific to druntime Druntime:AA Specific to Associative Arrays and removed enhancement labels Dec 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Druntime:AA Specific to Associative Arrays Druntime Specific to druntime P4 Severity:blocker Severity:Enhancement
Projects
None yet
Development

No branches or pull requests

2 participants