How to implement while loop in D?

I know that D already has a while loop, but because of its advanced functions, I would like to see how it would look if the while loop was implemented in the code.

motivation: accepted answer to this question on SO.

+5
source share
2 answers

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++;
    });
}
+10
source

using function with recursion: (tail call will be optimized;))

void whileLoop(bool delegate() cond,void delegate() fun){
    if(cond()){
        fun();
        whileLoop(cond,fun);
    }
}

should use closure

or always using excessively / underutilized goto

startloop:if(!condition)goto endloop;
//code
goto startloop;
endloop:;
+5
source

All Articles