Higher-order functions?
Nick Sabalausky
SeeWebsiteToContactMe at semitwist.com
Tue Apr 10 17:22:31 PDT 2012
"Jonas H." <jonas at lophus.org> wrote in message
news:mailman.1600.1334099651.4860.digitalmars-d-learn at puremagic.com...
> Hi everyone,
>
> does D have any runtime higher-order function facilities? (I'm not talking
> about templates.)
>
Yes. Fully. Many are already in the std lib:
http://dlang.org/phobos/std_algorithm.html
> More specifically, is something like this possible? (That's how I'd do it
> in Python)
>
> car_prices = map(Car.get_price, list_of_cars)
>
Just as one example (These all work as of DMD 2.058):
import std.algorithm; // For 'map'
class Car {...blah...}
int getPrice(Car c) {return ...blah...;}
void main()
{
auto listOfCars = [new Car()];
auto carPrices = listOfCars.map!getPrice();
}
Or:
import std.algorithm; // For 'map'
class Car
{
...blah...
@property int price() {return ...blah...;}
}
void main()
{
auto listOfCars = [new Car()];
auto carPrices = listOfCars.map!( (Car c) => (c.price) )();
//or
auto getPrice = (Car c) => (c.price); // getPrice can be reassigned
at runtime
auto carPrices = listOfCars.map!getPrice();
}
> car = new Car
> foobar(car.get_price)
class Car
{
...blah...
int getPrice() {return ...blah...;}
}
void foobar(int delegate() dg)
{
auto x = dg();
}
void main()
{
auto car = new Car();
foobar(&car.getPrice);
}
More information about the Digitalmars-d-learn
mailing list