Problem with closures: Problem solved

Bradley Smith digitalmars-com at baysmith.com
Thu Jan 11 09:48:05 PST 2007


Here is an alternate solution. One which requires fewer changes to the 
original design. Only the contents of the addN function have been 
changed. It is not necessarily better than the other solution. Just 
different.

import std.stdio;
alias int delegate(int x) AddFunc;

AddFunc addN(int n) {
     class A {
         int n;
         this(int n) {
             this.n = n;
         }
         int add(int i) {
             return i + n;
         }
     }
     A a = new A(n);
     return &a.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;
}

Alain wrote:
> David Medlock Wrote:
> 
>> D doesn't support true closures, just delegates.  Local variables in 
>> functions are still allocated on the stack and therefore invalid after 
>> you return from them.
>>
>> You must use objects for this purpose.
>>
>> -DavidM
> Thank you for the suggestion. I post hereunder my solution to the problem.
> 
> import std.stdio;
> 
> class ClassClosure
> {
>     this(int n)   { num = n;}
>     private uint num;  
>     int opCall(int x)  {return num+x;}
> }
> 
> void capply(int[] array, ClassClosure func) {
>     foreach (inout int i; array) { i = func(i); }
>     }
> 
> int main() {
>     int[] numbers = [1,2,3];
>     writefln("numbers before=",numbers);
>     ClassClosure myclosure= new ClassClosure(40);
>     capply(numbers, myclosure); // add 40 to each number
>     writefln("numbers after=",numbers);
>     return 0;
> }
> 
> Alain


More information about the Digitalmars-d-learn mailing list