Function literals -- strange behavior

Ary Borenszweig ary at esperanto.org.ar
Thu Dec 4 12:06:19 PST 2008


Justin wrote:
> I recently discovered D's function literals and wrote a small test to explore them. The following code prints out a 15, then a 0. It seems to me that the second should be 64 and not 0. Can anyone explain what I'm doing wrong?
> 
> 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;

That is:

total = 0

That's why in the second case it's like you are doing:

0*1*2*3*4

A reduce function normally takes the first value to use to reduce the 
others. So "total" would be an argument to your reduce function.


> 	foreach (int v; values)
> 		total = operation(total,v);
> 	return total;
> }



More information about the Digitalmars-d mailing list