I know D already has while loop, but because of its advanced 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.
Syntax of Do-While Loop in C:do { statements } while (expression); As we saw in a while loop, the body is executed if and only if the condition is true.
Syntax. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.
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:;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With