[Issue 13903] New: std.array.removeIf for associative arrays

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sat Dec 27 17:02:32 PST 2014


https://issues.dlang.org/show_bug.cgi?id=13903

          Issue ID: 13903
           Summary: std.array.removeIf for associative arrays
           Product: D
           Version: D2
          Hardware: x86
                OS: Windows
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: Phobos
          Assignee: nobody at puremagic.com
          Reporter: bearophile_hugs at eml.cc

A pattern in D code is to remove key-value pairs from an associative array
according to some given rule.

This pattern:
- Is sufficiently common in D code;
- It's bug prone because iterating an associative array you are removing items
from could cause troubles;
- It can be implemented with a simple clear function;
- It's often implemented not efficiently in user cose because sometimes you
solve the problem copying all the associative array, with memory-wasting code
like:

int[int] aa = ...;
foreach (key; aa.keys)
    if (predicate1(key))
        aa.remove(key);

foreach (key; aa.keys) {
    auto value = aa[key];
    if (predicate2(key, value))
        aa.remove(key);
}


So I suggest a function named like std.array.removeIf that accepts a predicate
with one or two arguments, if the predicate has one argument it receives the
key, otherwise it receives both key and value:

aa.removeIf!(key => key > 5);
aa.removeIf!((key, val) => key > val);

(The name of the function doesn't contain "associative array" because later an
overload of "removeIf" can be defined for dynamic arrays too).

--


More information about the Digitalmars-d-bugs mailing list