www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - return value

reply m <1234go1 gmail.com> writes:
Can a function return a function as a return value?
as a delegate?

thanks
M
Mar 09 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
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
next sibling parent m <1234go1 gmail.com> writes:
Thats Grate!!!

thanks
Mar 09 2010
prev sibling parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
bearophile wrote:
 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:
Is closure a separate feature, or are delegates closures? Thank you, Ali
Mar 09 2010
parent reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Tue, 09 Mar 2010 13:35:41 -0500, Ali Çehreli <acehreli yahoo.com> wrote:

 bearophile wrote:
 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:
Is closure a separate feature, or are delegates closures?
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. -Steve
Mar 09 2010
parent bearophile <bearophileHUGS lycos.com> writes:
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