How to implement while loop in D?
I know D already has while loop, but because of its advance开发者_JAVA百科d features I would like to see what it would look like if while loop was implemented in code.
motivation: the accepted answer to this question on SO.
Using lazy function parameters:
void whileLoop(lazy bool cond, void delegate() loopBody) {
Begin:
if(!cond) return;
loopBody();
goto Begin;
}
// Test it out.
void main() {
import std.stdio;
int i;
whileLoop(i < 10, {
writeln(i);
i++;
});
}
using a function with recursion: (tail call will get optimized ;) )
void whileLoop(bool delegate() cond,void delegate() fun){
if(cond()){
fun();
whileLoop(cond,fun);
}
}
closures should be used with that
or using the ever so over-/underused goto
startloop:if(!condition)goto endloop;
//code
goto startloop;
endloop:;
精彩评论