Can someone explain what is the difference between the two? Thanks.

module gates;
import std.stdio;
import std.random;

alias Calculator = int delegate(int);

Calculator makeCalculator()
{
    static int context = 0;
    int randy = uniform(1, 7);
    context++;
    writeln("context = ", context);
    writeln("randy = ", randy);
    return value => context + randy + value;
}

void main()
{
    for (int i = 0; i < 3; i++)
    {
        auto calculator = makeCalculator();
        writeln("The result of the calculation: ", calculator(0));
    }
}
returns:
context = 1
randy = 5
The result of the calculation: 6
context = 2
randy = 2
The result of the calculation: 4
context = 3
randy = 6
The result of the calculation: 9

while the following

void main()
{
auto calculator = makeCalculator(); // thought just one would work
    for (int i = 0; i < 3; i++)
    {
        writeln("The result of the calculation: ", calculator(0));
    }
}
returns:
The result of the calculation: 3
The result of the calculation: 3
The result of the calculation: 3


Reply via email to