Higher-order functions?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Apr 10 16:27:15 PDT 2012


On Wed, Apr 11, 2012 at 01:13:17AM +0200, Jonas H. wrote:
> Hi everyone,
> 
> does D have any runtime higher-order function facilities? (I'm not
> talking about templates.)
> 
> 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)
> 
> car = new Car
> foobar(car.get_price)
[...]

You can use delegates. Example:

	struct Car {
		int price;
		int wheels;

		int get_price() { return price; }
		int get_wheels() { return wheels; }
	}

	int sum(int delegate(Car) dg, Car[] cars) {
		int sum = 0;
		foreach (c; cars) {
			sum += dg(c);
		}
		return sum;
	}

	void main() {
		Car[] cars;
		cars ~= Car();
		... // add some stuff to the list

		int total_price = sum((Car c) => (c.get_price()), cars);
		int total_wheels = sum((Car c) => (c.get_wheels()), cars);
	}


T

-- 
IBM = I'll Buy Microsoft!


More information about the Digitalmars-d-learn mailing list