www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 13903] New: std.array.removeIf for associative arrays

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 puremagic.com
          Reporter: bearophile_hugs 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).

--
Dec 27 2014