5

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.

Community
  • 1
  • 1
Arlen
  • 6,641
  • 4
  • 29
  • 61
  • *n.b.* -- If anyone is wondering, the answer referred to as motivation is about Haskell, which I assume is why this is tagged as such. – C. A. McCann Jul 14 '11 at 02:33
  • @camccann True. I've begun learning Haskell, and I know enough D to make me want to see while loop implemented in D just for comparison sakes. – Arlen Jul 14 '11 at 02:41
  • It's fine. Just wasn't clear from the question why it was tagged [haskell], the comment was aimed at people reading the question, not you. Though it might not hurt to add some details (e.g., that the other question has Haskell code, that you're interested in a comparison, etc.). – C. A. McCann Jul 14 '11 at 02:45
  • @Arlen: The purpose of tagging a question as "Haskell" is to bring people interested in Haskell to the question. These people are quite surprised that the question is not about Haskell. – Dietrich Epp Jul 14 '11 at 04:47

2 Answers2

10

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++;
    });
}
dsimcha
  • 67,514
  • 53
  • 213
  • 334
5

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:;
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • 1
    "tail call optimization" [citation needed]? – BCS Jul 14 '11 at 15:31
  • @BCS the recursive call will be transformed to a `goto` to the start of the function and no stack overhead will be created during recursion (this can be done when no stack teardown code needs to execute on return) – ratchet freak Jul 14 '11 at 18:15
  • OK I guess I was ambiguous. What I was getting at was; Is that an implementation detail of DMD or does D require that it be done? -- If it is the former, that can fail with conforming compilers. If it is the latter, please provide a link. – BCS Jul 14 '11 at 21:12
  • 1
    @BCS any decent compiler with any optimization can do this, but indeed it's a detail of DMD and not D – ratchet freak Jul 14 '11 at 22:35