The Many Faces of D - slides
Simen kjaeraas
simen.kjaras at gmail.com
Sun Oct 3 08:07:02 PDT 2010
Russel Winder <russel at russel.org.uk> wrote:
> def sumOfSquares ( sequence ) :
> return sum ( [ item * item for item in sequence ] )
> So the question is whether there is an idiomatic D version of this.
Probably this:
auto sum( R )( R range ) {
return reduce!"a+b"( 0, range );
}
auto sumOfSquares( R )( R range ) {
return sum( map!"a*a"( range ) );
}
I have written an implementation of list
comprehensions for D, but it is not perfect.
Usage example:
( list!"2 * a" | [1,2,3,4,5] & where!"a & 1" )
"2 * a" and "a & 1" may be replaced by any callable or a string
mixin, just like functions in std.algorithm.
[1,2,3,4,5] may be replaced with any range.
This is actually two parts, so the following are also allowed
usages:
( list!"2 * a" | [1,2,3] )
( [1,2,3] & where!"a & 1" )
Using this, the solution to the above would be:
auto sum( R )( R range ) {
return reduce!"a+b"( 0, range );
}
auto sumOfSquares( R )( R range ) {
return sum( list!"a*a" | range );
}
////////////////////////////////////////////////////////////////
module listcomp;
import std.algorithm;
import std.range;
import std.array;
struct List( alias pred ) {
auto opBinary( string op : "|", Range )( Range other ) {
return map!pred(other);
}
}
struct Where( alias pred ) {
auto opBinaryRight( string op : "&", R )( R range ) {
return filter!pred(range);
}
}
@property
whereImpl!pred where( alias pred )( ) {
Where!pred result;
return result;
}
@property
listImpl!pred list( alias pred )( ) {
List!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