Thread overview
return value
Mar 09, 2010
m
Mar 09, 2010
bearophile
Mar 09, 2010
m
Mar 09, 2010
Ali Çehreli
Mar 09, 2010
bearophile
March 09, 2010
Can a function return a function as a return value?
as a delegate?

thanks
M
March 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
March 09, 2010
Thats Grate!!!

thanks
March 09, 2010
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
March 09, 2010
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
March 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