List comprehensions in D?

David Medlock noone at nowhere.com
Tue Jun 27 05:04:31 PDT 2006


David Medlock wrote:
> 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

Another useful pair of templates for parsing: skip and collect

// skip whitespace during parsing
char[] r = text.skip( (char c){ return c<=32; } );

// get the next token from the input text
char[] tok = text.collect( (char c){return isalnum(c)!=0; } );

template skip(T)
{
   T[]  skip( T[] arr, bool delegate(T) dg )
   {
     int count = 0;
     foreach( T val; arr ) if ( dg( arr[count] )) count++; else break;
     return arr[count..arr.length];
   }
}

template collect(T)
{
   T[]  collect( T[] arr, bool delegate(T) dg )
   {
     int count = 0;
     foreach( T val; arr ) if ( dg( arr[count] )) count++; else break;
     return arr[0..count];
   }
}


Love the new syntax, so clean.
-DavidM



More information about the Digitalmars-d mailing list