## digitalmars.D - map & filter for AAs

• spir (41/41) Feb 08 2011 Hello,
• bearophile (5/6) Feb 08 2011 Of course it's useful to map and filter on associative arrays. But I thi...
spir <denis.spir gmail.com> writes:
```Hello,

Is there map & filter for AAs? Is it useful?
Below example,
Denis

struct Pair (K,V) { K k; V v; }

V2[K2] map (K1,V1, K2,V2) (V1[K1] aa1, Pair!(K2,V2) delegate (K1,V1) f) {
V2[K2] aa2;
Pair!(K2,V2) pair;
foreach (k,v ; aa1) {
pair = f(k,v);
aa2[pair.k] = pair.v;
}
return aa2;
}

V1[K1] filter (K1,V1) (V1[K1] aa1, bool delegate (K1,V1) f) {
V1[K1] aa2;
foreach (k,v ; aa1) {
if (f(k,v))
aa2[k] = v;
}
return aa2;
}

unittest {
char[uint] aa1 = [65:'a', 66:'b', 67:'c'];

// map
Pair!(char,uint) inversed (uint u,char c) { return Pair!(char,uint)(c,u); }
auto aa2 = map!(uint,char, char,uint)(aa1, &inversed);
writefln("map inversed  : [%s] --> [%s]", aa1,aa2);

// filter
bool odd (uint u,char c) { return (u%2 == 1); }
auto aa3 = filter!(uint,char)(aa1, &odd);
writefln("filter odd    : [%s] --> [%s]", aa1,aa3);
bool c (uint u,char c) { return (c == 'c'); }
auto aa4 = filter!(uint,char)(aa1, &c);
writefln("filter c      : [%s] --> [%s]", aa1,aa4);
}
void main() {}

--
_________________
vita es estrany
spir.wikidot.com
```
Feb 08 2011
bearophile <bearophileHUGS lycos.com> writes:
```spir:

Is there map & filter for AAs? Is it useful?

Of course it's useful to map and filter on associative arrays. But I think a
much better solution is to turn byValue() and byKey() into ranges, and add a
byPair() range to AAs:
http://d.puremagic.com/issues/show_bug.cgi?id=5466

Bye,
bearophile
```
Feb 08 2011