Function literals -- strange behavior
Christopher Wright
dhasenan at gmail.com
Thu Dec 4 15:24:04 PST 2008
Justin wrote:
> Ahh, I thought it would some stupid oversight on my part. This works:
>
> module functionliteral;
>
> import std.stdio;
>
> static void main() {
>
> int[] values = [1,2,4,8];
> writefln(Reduce(values, function int(int x, int y) { return x + y; }));
> writefln(Reduce(values, function int(int x, int y) { return x * y; }));
> }
>
> static int Reduce(int[] values, int function(int x, int y) operation) {
> int total = values[0];
> foreach (int v; values[1..$])
> total = operation(total,v);
> return total;
> }
>
You don't need to make those static, by the way.
Reduce doesn't work on all inputs:
writefln(Reduce([], (int x, int y) { return x + y; }));
More information about the Digitalmars-d
mailing list