digitalmars.D.learn - return value
- m (4/4) Mar 09 2010 Can a function return a function as a return value?
- bearophile (12/14) Mar 09 2010 Yes, you can do those things. In D2 you can return a clusure too:
- m (2/2) Mar 09 2010 Thats Grate!!!
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (4/9) Mar 09 2010 Is closure a separate feature, or are delegates closures?
- Steven Schveighoffer (22/28) Mar 09 2010 A closure is a separate feature.
- bearophile (4/5) Mar 09 2010 But for me it's not always easy to ask the compiler if you want it or a ...
Can a function return a function as a return value? as a delegate? thanks M
Mar 09 2010
m Wrote:Can a function return a function as a return value? as a delegate?Yes, you can do those things. In D2 you can return a clusure too: import std.stdio: writeln; auto adder(int x) { return (int y) { return x + y; }; } void main() { auto adder5 = adder(5); writeln(adder5(3)); // prints 8 } Bye, bearophile
Mar 09 2010
bearophile wrote:m Wrote:Is closure a separate feature, or are delegates closures? Thank you, AliCan a function return a function as a return value? as a delegate?Yes, you can do those things. In D2 you can return a clusure too:
Mar 09 2010
On Tue, 09 Mar 2010 13:35:41 -0500, Ali Çehreli <acehreli yahoo.com> wrote:bearophile wrote:A closure is a separate feature. Basically, a closure is a delegate with a stack frame that is allocated on the heap. The advantage is you can pass it around and not worry about the context becoming invalid. In D1, for example, you could do what bearophile did, but it would result in memory corruption: void delegate(int) adder(int x) { void dg(int y) { return x + y; } return &dg; } The problem with this is that x is valid in the context of foo, not the context of the delegate. Therefore, when foo returns, it's stack-based frame can be overwritten, corrupting the value for x. In D2, the above code makes the D compiler allocate foo's stack frame on the heap, so even when foo returns, its stack frame is valid for the delegate to refer to. -Stevem Wrote:Is closure a separate feature, or are delegates closures?Can a function return a function as a return value? as a delegate?Yes, you can do those things. In D2 you can return a clusure too:
Mar 09 2010
Steven Schveighoffer:A closure is a separate feature.But for me it's not always easy to ask the compiler if you want it or a not-closure delegate is enough. It's not a tidy situation. Bye, bearophile
Mar 09 2010