Proposal of a general do-while loop
janderson
askme at me.com
Sat Jul 21 12:25:45 PDT 2007
downs wrote:
> Taro Kawagishi wrote:
>> I think a more natural way to express the logic is to write the code
>> as in listing 4.
>>
>> // listing 4
>> size_t pos = 0;
>> do {
>> pos = text.find(pattern, pos);
>> } while (pos != string::npos) {
>> cout << "pattern found at " << pos << "\n";
>> ++pos;
>> }
>>
>> The meaning of
>>
>> do {
>> aa;
>> } while (bb) {
>> cc;
>> }
>>
>> is
>>
>> while (true) {
>> aa;
>> if (not bb) {
>> break;
>> }
>> cc;
>> }
>
> void doWhile(void delegate() pre, lazy bool cond, void delegate() post) {
> while (true) {
> pre;
> if (!cond()) break;
> post;
> }
> }
>
> // listing 4, modified
> size_t pos=0;
> doWhile ({
> pos=text.find(pattern, pos);
> }, pos!=string::npos, {
> writefln("Pattern found at ", pos);
> ++pos;
> });
>
> Not tested, but should work.
> Have fun!
Nice. Not that I really think we need this new construct however this
is what I was thinking. (untested)
struct WhileStruct
{
void delegate() pre;
bool delegate() cond;
void opCall(void delegate() post)
{
while (true)
{
pre();
if (!cond()) break;
post();
}
}
}
struct Do
{
void delegate() pre;
static Do opCall(void delegate() pre) //could be a free function
{
Do d;
d.pre = pre;
return d;
}
WhileStruct While(lazy bool cond)
{
WhileStruct w;
w.pre = pre;
w.cond = {return cond();};
return w;
}
}
void main()
{
// Do({...}). //Note that "dot" is the nastiest part
// While(...)({...});
//ie
Do({pos=text.find(pattern, pos);}).
While(pos != string::npos)
({
writefln("Pattern found at ", pos);
++pos;
});
}
Here are some other forms I think would be possible to code in a library
in D.
Do({...})(...)({...});
Do[{...}]()[{...}];
Do({...})
(While(...))({...});
while (Do(..., {...}))
{
};
Do({...}) = While(...)
({});
Do({...}) = (...) = ({});
Do({...}) ~ (...) ~ ({});
Do({...}); //Essentially stores a delegate on the stack
While(...)
({...});
The power of D.
More information about the Digitalmars-d
mailing list