The Many Faces of D - slides

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sun Oct 3 10:25:03 PDT 2010


On 10/03/2010 10:21 AM, Simen kjaeraas wrote:
> Simen kjaeraas <simen.kjaras at gmail.com> wrote:
>
>> 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 );
>> }
>
> Sorry, code was wrong. Update:
>
>
> 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
> auto where( alias pred )( ) {
> Where!pred result;
> return result;
> }
>
> @property
> auto 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] ) );
> }

I wonder to what extent this improves

assert(equal(map!"2 * a"(filter!"a & 1"([1,2,3,4,5])), [2,6,10]));

One thing that's nicer with comprehensions is that you save a bit on 
nested parens.


Andrei


More information about the Digitalmars-d mailing list