Idea: "Frozen" inner function

Michael Butscher mbutscher at gmx.de
Sat Nov 25 05:41:49 PST 2006


Steve Horne wrote:
> On Fri, 24 Nov 2006 21:59:33 +0100, Michael Butscher
> <mbutscher at gmx.de> wrote:
> 
> >An inner function could get "frozen" as some kind of storage class 
> >which means that all variables accessed by the inner function which are 
> >defined in the surrounding function keep the value they had at the 
> >point in time when the inner function was defined.
> 
> It's called a closure.
> 
> D inner functions seem to borrow a lot from the Pascal family
> languages. These have inner functions, but don't have closures. It
> simply isn't the done thing to call these inner functions using a
> pointer after the outer function had exited - it isn't part of
> structured programming.
> 
> Closures originally came about in languages that have 'first class
> functions' - functional languages. These days, some scripting
> languages have them - Python uses them for 'lambda' anonymous
> functions, for instance.

I heard about closures already, but I thought that they are different 
from inner functions only by surviving the end of the outer function.

Especially a closure would have direct access to the current value of 
local variables of the outer function (if it exists yet) which is not 
the case for frozen functions.


> But it is a trade-off between efficiency and flexibility. D currently
> goes with efficiency by default, but you can explicitly create an
> inner function with a closure if you need one - though its not very
> convenient.

The only efficiency tradeoff of frozen functions is the copying at the 
time of definition (and later the freeing of the context memory). 
Except for that they would be as efficient as inner functions.


> Tip - use an anonymous class with a function-call method.

This would be technically the same, but, as you wrote, less convenient.



Michael



More information about the Digitalmars-d mailing list