Idea: "Frozen" inner function

Michael Butscher mbutscher at gmx.de
Fri Nov 24 12:59:33 PST 2006


Hi,

this is yet another idea how to return delegates from a function 
without destroying the context (which could be on the stack).


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.

Technically the context pointer of the inner function would point to an 
area on the heap. When the point of definition of the inner function is 
reached (which can happen multiple times) the needed variables are 
copied from the stackframe of the outer function to the context area of 
the inner function on the heap.



Example:


import std.stdio;

void main()
{
    int i = 0;
    
    while (i < 10)
    {
        frozen void pr() // when reached, i is copied to context
        {
            writef(i, " ");
        }
        
        ++i;  // pr() doesn't care about this change
        pr();
    }
}

Without "frozen" this prints:
1 2 3 4 5 6 7 8 9 10

With "frozen" this would print:
0 1 2 3 4 5 6 7 8 9


Of course you would put the definition only inside such a loop if you 
need it for some special reason.



Maybe it would also be desirable to trigger the copying of stackframe 
data at another point than function definition.

For this, a property "freeze" could be created for the inner function, 
so the above code could also look like:


import std.stdio;

void main()
{
    int i = 0;

    frozen void pr()
    {
        writef(i, " ");
    }
    
    while (i < 10)
    {
        pr.freeze;
        ++i;  // pr() doesn't care about this change
        pr();
    }
}


But this might be more complicated as the scope at function definition 
could be another than at the "freeze" call.



Michael



More information about the Digitalmars-d mailing list