real simple delegate question.

angel via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 18 13:39:38 PDT 2017


On Friday, 18 August 2017 at 02:38:15 UTC, WhatMeForget wrote:
>
> 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

This actually appears correct ...
The 1-st example:
Each call to makeCalculator() increments a static (i.e. shared 
among all makeCalculator() instances) variable - context.
In addition, makeCalculator() generates a random variable.
Whereas the delegate merely captures these variables, and the 
displayed results reflect this.

The 2-nd example:
There is a single call to makeCalculator().
After this call, context == 1, randy == _apparently 2_.
Now the delegate, as has already been said, merely captures these 
values, so consecutive calls do not change the result.


More information about the Digitalmars-d-learn mailing list