Steve Yegge's rant on The Next Big Language

Foo foo at bar.zoo
Mon Mar 12 06:34:39 PDT 2007


janderson Wrote:

> Jarrett Billingsley wrote:
> > 
> > Basically it's a way of really easily applying functions and such over a 
> > list.  They're kind of like array operations (a[] = b[] + c[]), which D 
> > doesn't have yet, but more flexible.  You can do stuff like (using very 
> > python-like syntax):
> > 
> > int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8];
> > 
> > // This loops through numbers, seeing if the condition holds true,
> > // and if it does, adds it to a new list, which is eventually assigned
> > // to evens.
> > int[] evens = [x for x in numbers if !(x & 1)];
> > 
> > // Square the list
> > int[] squares = [x * x for x in numbers];
> 
> I'm not sure about these.  The syntax is not much better then a foreach 
> loop.

We can use "Array operations":

R[] map(T,R)(T[] arr, R delegate(T) dg){
    R[] result = new R[arr.length];
    foreach(i, item; arr)
        result[i] = dg(item);
    return result;
}

void main(){
    int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8];
    int[] squares = numbers.map( delegate int(int x){return x * x;} );
}

I think the syntax of delegate literal should be simplified, like this:
int[] squares = numbers.map( int(int x){return x * x;} );

or ruby-like syntax:
int[] squares = numbers.map( {int|int x| x * x} );



More information about the Digitalmars-d-announce mailing list