Huffman coding comparison
Simen kjaeraas
simen.kjaras at gmail.com
Fri May 28 18:11:15 PDT 2010
bearophile <bearophileHUGS at lycos.com> 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
More information about the Digitalmars-d
mailing list