weird behavior returning delegate

Carlos Santander csantander619 at gmail.com
Sat Jul 1 10:22:19 PDT 2006


Sean Kelly escribió:
> Carlos Santander wrote:
>> This code, with DMD 0.162 on Windows:
>>
>> //-----------------------
>> T delegate (T) acc (T) (T n)
>> {
>>     return (T i) { return n += i; };
>> }
>>
>> void foo ()
>> {
>>     auto acc1 = acc (4);
>>     assert (5 == acc1 (1), "5 != 5");
>>     assert (7 == acc1 (2), "7 != 7");
>>
>>     auto acc2 = acc (10);
>>     assert (11 == acc2 (1), "11 != 11");
>>     assert (12 == acc2 (1), "12 != 12");
>>
>>     assert (10 == acc1 (3), "10 != 10"); // 16
>>     assert (20 == acc2 (8), "20 != 20");
>> }
>>
>> import std.stdio;
>>
>> void bar ()
>> {
>>     auto acc1 = acc (4);
>>     writefln (" 5 == %s", acc1 (1));
>>     writefln (" 7 == %s", acc1 (2));
>>
>>     auto acc2 = acc (10);
>>     writefln ("11 == %s", acc2 (1));
>>     writefln ("12 == %s", acc2 (1));
>>
>>     writefln ("10 == %s", acc1 (3));
>>     writefln ("20 == %s", acc2 (8));
>>     writefln ();
>> }
>>
>> void main()
>> {
>>     bar ();
>>     foo ();
>> }
>> //-----------------------
>>
>> Produces this:
>>
>>  5 == 5
>>  7 == 10
>> 11 == 11
>> 12 == 9
>> 10 == 13
>> 20 == 17
>>
>> Error: AssertError Failure test.d(16) 10 != 10
>>
>> I think the assert failing is somewhat expected (stack frame no longer 
>> available), but how can the previous asserts work when the values 
>> shown with writefln are not the ones expected, or supposedly asserting 
>> correctly?
> 
> It's because you're using one function to do the asserts and another to 
> print results, so the values returned from acc1 and acc2 may be 
> different.  I combined the two cases by storing the result in a number 
> then performing the assert, etc, and the errors corresponded with what 
> was displayed.
> 
> 
> Sean

I did the same too, but that's what I don't understand: what are really the 
correct values, the ones that are printed or the ones that pass the asserts?

Also, I don't think putting them in one, two or more functions really matters. I 
would expect the previous acc1 and acc2 to be gone when the function exits.

Anyway, bottom line is I think I'm hoping for too much. Unless something like 
Burton's proposed "new delegate" syntax is put into the language, this wouldn't 
really work properly.

-- 
Carlos Santander Bernal



More information about the Digitalmars-d mailing list