Control Structures Proposal

janderson askme at me.com
Tue Jul 24 22:40:29 PDT 2007


I know creating user control structures has been talked about before.

Anyways something to chew on, it occurs to me that D almost has the 
power to create these structures.

For example you can currently do something like this in D (untested).

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


});


or

If (X)
({

}).
Else
({

));

I was thinking if D provided a block operator like opCall then we would 
be much closer to getting this flexibility.

the syntax would be:

struct [name of struct]
{
	static [returntype] opBlock(void delegate() block, [, parm, param, ...]);
}

ie:

struct For
{
	static void opBlock(void delegate() block, void delegate() init, lazy 
bool condition, void delegate() iteration)
{
	...
}

};

//Then we could write:

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

}

The next thing that could be done to improve this is to allow all single 
terms to be turned into delegates automatically, like lazy works so we 
don't have to provide the {}.  ie this should then work:

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

}

The last thing that would be necessary to complete the picture is to 
allow contacted statements (like Else in for loop).  This is the most 
difficult syntax to figure out (Any ideas?).  I think the return type 
from the opBlock is one idea, however it suffers from the fact that all 
the processing is done in the second struct its pretty odd.  Perhaps


struct [name of struct]
{
	static [returntype] opBlock(void delegate() block, [, void delegate() 
blockname2, void delegate() blockname3, ...] [, parm, param, ...]);
}

//ie If Else

struct If
{
	static void opBlock(void delegate() block, void delegate() Else);
}

Of course that would mean someone could write my forloop example like 
this as well :(

For (i!=0, ++i)
{

}
init
{
	int i = 0;
}

Ug.


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

-Joel



More information about the Digitalmars-d mailing list