The future of lambda delegates
nobody
nobody at mailinator.com
Thu Aug 17 11:55:59 PDT 2006
Regan Heath wrote:
> On Thu, 17 Aug 2006 01:15:15 +0100, Bruno Medeiros
> <brunodomedeirosATgmail at SPAM.com> wrote:
>>
>> For starters, a delegate can access the outer function arguments, but
>> those arguments cannot be made static.
>>
>> And then there will only be one "instance" of the returned delegate
>> (think of the delegate as an object). Any call to it will update only
>> one single sequence:
>>
>> auto dg1 = fibs();
>> auto dg2 = fibs();
>> dg1(); // 1
>> dg1(); // 2
>> dg2(); // 3
>> dg2(); // 5
>>
>> However, with proper "heaped" frames, there are many delegate (outer
>> frame) "instances":
>>
>> auto dg1 = fibs();
>> auto dg2 = fibs();
>> dg1(); // 1
>> dg1(); // 2
>> dg1(); // 3
>> dg2(); // 1
>> dg2(); // 2
>> dg2(); // 3
>
> So, the other option is:
>
> import std.stdio;
>
> // The Fibonacci numbers are an integer sequence such that
> // F(n) = F(n - 1) + F(n - 2)
> // And F(0) = 0, F(1) = 1
> int delegate(inout int,inout int) fibs()
> {
> return (inout int a, inout int b)
> {
> int c = a + b; // Calculate the next term in the sequence
> a = b; // Shift the previous terms back
> b = c;
> return c; // Return the result
> };
> }
>
> ...
>
> Right? Passing the storage location to the calls.
>
> Regan
Not sure if you figured it out on your own but I thought maybe someone else
might have the same question. The short answer is that the delegate Mikola
Lysenko was attempting to define evaluates the first time it is called to the
first number in a sequence, S(1), and thereafter the Nth evaluation yields S(N).
The delegate you defined starts with two arbitrary params -- which can but
needn't be the start of the sequence. This implementation requires somebody
using your function to know what magic numbers start the whole thing off and
requires you to test for strange values.
The entire challenge is really that there is no reason to pass arguments to
Mikola Lysenko's function because it should know where it starts, how to
progress from any N to N+1 and finally remember the last N for which it was
evaluated.
More information about the Digitalmars-d
mailing list