DMD 0.166 release
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Fri Sep 1 06:11:29 PDT 2006
Ivan Senji wrote:
> Walter Bright wrote:
>
>> The implicit conversion to delegate just broke too much. Instead, I'm
>> trying out Tom S.'s suggestion of using a 'lazy' parameter storage class.
>>
>> http://www.digitalmars.com/d/changelog.html
>
>
> Hmm, I am afraid I have to admit I'm a little bit puzzled by this lazy
> thing.
>
> Let's say we have:
>
> void dotimes(int count, lazy void exp)
> {
> for (int i = 0; i < count; i++)
> {
> exp();
> }
> }
>
> and I can call it like this:
>
> int x;
> dotimes(5, x++);
>
> And it works as expected and x end up being 5.
>
> But shouldn't I also be allowed to pass in a delegate of the appropriate
> type
>
> dotimes(5, {writefln(x); x++;});
>
> A funny thing happens: nothing. The loop in dotimes does get executed 5
> times but delegate passed in isn't called?
>
>
This is because anonymous delegates are themselves expressions, and so your 'exp()' just
evaluates to the delegate itself -- it does not invoke it. However, to achieve what you
were trying to do, just make use of parentheses and the comma operator. Also, you may
provide an overload that takes a lazy delegate. Here is my own test program, which worked
without issue:
# module lazy1 ;
#
# import std .stdio ;
#
# void dotimes (int count, lazy void exp) {
# while (count--) exp();
# }
#
# void dotimes (int count, lazy void delegate() exp) {
# while (count--) exp()();
# }
#
# void main () {
# int x;
# dotimes(5, x++);
# writefln("x is now: ", x);
#
# int y;
# dotimes(5, (writefln("[y] ", y), y++));
# writefln("y is now: ", y);
#
# int z;
# dotimes(5, {writefln("[z] ", z); z++;});
# writefln("z is now: ", z);
# }
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-announce
mailing list