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