February 10, 2006 Re: From stack delegates to true closures | ||||
---|---|---|---|---|
| ||||
Posted in reply to Søren J. Løvborg | In article <drod3j$1jm0$1@digitaldaemon.com>, S�ren J. L�vborg says... > >I'm aware this has been discussed before, but I'd like to bring it up again (sorry!): D really should have true closures, or "stack delegates that can be returned" if you will. > >First of all, they're a very useful feature, allowing short and concise code. >One option to work around this might be to add new syntax, say "new delegate" for this new behaviour, if implemented. > >Any comments? Am I the only one who'd find this useful? Is there already similar functionality, and I've just not found it? (If so, please elaborate!) > >S�ren J. L�vborg >web@kwi.dk > > It is very useful as I see it. I recently looked at D at found it very promising (being disappointed in C++, after all these years). Currently, I use Python in my projects, and these "true" closures are quite natural in Python: def make_adder(n): def _adder(m): return n + m return _adder adder = make_adder(3) print adder(2) gives 5. (Sorry for this alien language snippet). Looking for something faster than Python, I tried to do that in D, but no way: import std.stdio; int delegate(int) make_adder(int what) { int _adder(int num) { return what + num; } return _adder; } void main() { int delegate(int) adder; adder = make_adder(3); writefln("%d", adder(2)); // Oops! the stack frame is gone :( } And worse, this doesn't work too: int delegate(int) make_adder(int what) { int *pw = new int; *pw = what; int _adder(int num) { return *pw + num; // Doesn't work either - the *pw is corrupted // after exiting the stack frame } return _adder; } About syntax, it would be convenient it I had another storage modifier, like "managed": int delegate(int) make_adder(managed int what) { int _adder(int num) { return what + num; // "What" is allocated on the heap // and managed with GC } return _adder; } Just my $0.02, and sorry for bad English. -- Eugene |
Copyright © 1999-2021 by the D Language Foundation