Control Structures Proposal

Reiner Pope some at address.com
Wed Jul 25 00:33:15 PDT 2007


I like the idea of adding more allowable operator overloads -- it's a 
relatively easy way to allow more user-defined syntaxes.

However, I think delegates is the wrong level to deal with control 
structures, for two main reasons: there's no ability to do manipulation 
of scope; and you lose information by expressing it all in terms of a 
delegate: the runtime nature of delegates is not required for control 
structures, since their backing code (the block) is inherently known at 
compile time. For these reasons, I think manipulation of D code (via 
char[]s and mixin at present) is better than manipulation of compiled 
code aka delegates/funcptrs. I suspect (and hope) that such manipulation 
of code is what AST macros are going to provide, improving on char[] 
mixins by keeping the manipulation entirely in the AST domain, and 
giving it a nicer syntax.

Your examples which work through delegates suffer the impossibility of 
declaring the increment variable in the For loop:

> For({int i=0;}, i!=0, {++i})
> ({
> 
> 
> });

this kind of thing won't work, because the declaration of i is scoped to 
the first delegate, and is invisible to the following two delegates. I 
believe this is an inherent problem of delegates can't be solved 
(although it can be worked around, as downs did, by declaring i earlier).

Additionally, having access to the *code* rather than just the delegate 
allows the type system required by the delegate to be made more generic. 
In fact, it isn't too hard to implement foreach-on-tuples with string 
mixins to support the following:

void main()
{
     alias Tuple!(int, double) T;
     T t;
     t[0] = 5;
     t[1] = 15.0;

     mixin(Foreach( "x", "t", `x *= 3;` ));

     writefln("%s %s", t); // prints 15 45
}
(implementation attached)

A delegate can't express the notion in the above example that the code 
"x *= 3" is valid both for ints and doubles; however, manipulation of 
code can.



> (PS I know lazy may be removed in the future, I hope normal delegates 
> will work as its replacement).

Yes, I hope so too.


   -- Reiner



More information about the Digitalmars-d mailing list