List comprehensions in D?

David Medlock noone at nowhere.com
Sun Jun 25 09:22:53 PDT 2006


My meager attempts to clone some list functionality in Python:

r = [ y for y in array if y > 10 ];

thanks to shortened delegate declarations its pretty close in D:
(this is a first stab but I'm sure we can get closer with some hackery)

int[] r = array.where( (int y){ return y>10; } );

and for mutating the array:

int[] r = array.map( (int y){return y + 5;} );

and in place modifications:

array.update( (inout int y){ y+=5; } );


// template code begins

template where(T)
{
   T[]   where( T[] arr, bool delegate(T) dg )
   {
     T[] result ;
     foreach( T val; arr ) if ( dg(val) ) result ~= val;
     return result;
   }
}

template  map(T)
{
   T[]   map( T[] arr, T delegate(T) dg )
   {
     T[] result = new T[arr.length];
     for( int n =0; n<arr.length; n++ ) result[n] = dg(arr[n]);
     return result;
   }
}

template update(T)
{
   void  update( T[] arr, void delegate(inout T) dg )
   {
     foreach( int n,T val; arr ) dg( arr[n] );
   }
}

Pretty cool, IMO.
-DavidM



More information about the Digitalmars-d mailing list