bearophile <[email protected]> wrote:
I will keep missing array comprehensions in D. In the meantime other
languages have got some forms of them (but Python ones use the best
syntax still).
I'm now so tired of hearing this, I started writing something that
does it:
auto r = list!"2 * a" | [1,2,3,4,5] & where!"a & 1" );
Takes any kind of range, and list and where are basically map and
filter in disguise. Only thing I did was add operator overloading.
Now, granted, I have little to no experience with list comprehension,
and as such this might not be what is needed. Still, it was fun to
play around with, and I kinda like what it turned out as.
import std.algorithm;
import std.range;
import std.array;
struct listImpl( alias pred ) {
auto opBinary( string op : "|", Range )( Range other ) {
return map!pred(other);
}
}
struct whereImpl( alias pred ) {
auto opBinaryRight( string op : "&", R )( R range ) {
return filter!pred(range);
}
}
@property
whereImpl!pred where( alias pred )( ) {
whereImpl!pred result;
return result;
}
@property
listImpl!pred list( alias pred )( ) {
listImpl!pred result;
return result;
}
unittest {
assert( equal( list!"2 * a" | [1,2,3,4,5] & where!"a & 1", [2,6,10] )
);
assert( equal( list!"2 * a" | [1,2,3], [2,4,6] ) );
}
--
Simen