Problem with closures
Alain
alainpoint at yahoo.fr
Thu Jan 11 02:19:01 PST 2007
Hello,
I am experimenting with closures and i have problem with the following code:
import std.stdio;
alias int delegate(int x) AddFunc;
AddFunc addN(int n) {
int add(int i) {
return i + n;
}
return &add; // the add function captured will remember the value of n
}
void apply(int[] array, AddFunc func) {
foreach (inout int i; array) {
i = func(i);
}
}
int main() {
int[] numbers = [1,2,3];
writefln("numbers before=",numbers);
apply(numbers, addN(40)); // add 40 to each number
writefln("numbers after=",numbers);
return 0;
}
The result should be [41,42,43] but i get [4202694,4202695,4202696]
Am i missing something?
Alain
More information about the Digitalmars-d-learn
mailing list