Control Structures Proposal

janderson askme at me.com
Wed Jul 25 22:25:57 PDT 2007


Reiner Pope wrote:
> Reiner Pope wrote:
>> I like the idea of adding more allowable operator overloads -- it's a 
>> relatively easy way to allow more user-defined syntaxes.
>>
> I had meant to expand on this point, but I forgot about it. I wanted to 
> say that operator overloads can provide syntaxes for common things 
> without requiring heavy features like AST macros. I think this is a good 
> thing, and I believe that enough can be done with block structures to 
> warrant including them as an operator overload.
> 
> However, owing to the scoping issues I mentioned in my previous post, I 
> think your approach is not quite ideal, and I think a preferable 
> approach (although humbler and more limited) would be trailing 
> delegates, which has been discussed a few times in the past.
> 
> Trailing delegates solve the scope issue by cheating: we say, "it is 
> common to declare some variables which are accessed by the following 
> block, so we will make a special-case syntax for that." By doing this, 
> you get a syntax something like:
> 
> myList.each() (i)  // i is declared here, but type-inferred like foreach
> // (the first parentheses may be omitted as per normal function calls)
> {
>     writefln(i);
> }
> 
> While the normal reaction is that such special cases are bad, I would 
> argue the contrary, because that is the essence of operator overloading: 
> a combination of special case syntaxes can lead to a variety of useful 
> results.
> 
>   -- Reiner


You rise a good point.

I was thinking if perhaps D could allow scope-less delegates that only 
have one sequence of commands (ie int i  or int i, int j would be 
considered one sequence) Then if there was a sequence of sequenced 
delegates (ie For(void delegate(), void delegate())) everything passed 
in would be in the same scope of the params.  However I realize that may 
be tricky to do.

However another thought would be to simply have to do int i outside the 
for loop.  Not so nice but its a start on the right track.   Maybe the 
best way of doing things though is to use a template as others have 
suggested in the past.

void For(block ini, block cond, block itr)(void delegate() inner)
{
	for (int, cond, itr) inner();
}

But that requires a new term as opposed to a new operator and also the 
delegate to be allowed to be after the function.

ie:

For (int i=0, i<10, ++i)
{

}

//This would also work:

void Test(void delegate() inner) {...}

Test{  ...  }

Not too bad actually.  Essentially its simply stripping the ();.  You 
could also do the "Else" sort of thing in the same way I suggested 
before.  I think that is a better solution then having an operator.

-Joel



More information about the Digitalmars-d mailing list