Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement while loop in D?

Tags:

while-loop

d

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.

like image 392
Arlen Avatar asked Jul 14 '11 02:07

Arlen


People also ask

What is the syntax of while loop?

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.

What are the steps to do while loop?

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.


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++;
    });
}
like image 75
dsimcha Avatar answered Oct 08 '22 03:10

dsimcha


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:;
like image 25
ratchet freak Avatar answered Oct 08 '22 02:10

ratchet freak