Proposal of a general do-while loop [more generic and tested version]

downs default_357-line at yahoo.de
Tue Jul 17 14:24:17 PDT 2007


Here's a more generic version. This one was tested and shown to work.
Have fun with it!
  --downs
=======================================================================
import std.stdio, std.string;

/// Cond is
void doWhile(P, C, O)(lazy P pre, lazy C cond, lazy O post) {
   while (true) {
     static if (is(P==void delegate())) pre()(); else pre();
     if (!cond()) break;
     static if (is(O==void delegate())) post()(); else post();
   }
}

// these are the things stupid std.string forces us to do.
// Tango, with str.length==NOTFOUND, really picked the better approach.
int find(char[] str, char[] match, int offset) {
   auto res=std.string.find(str[offset..$], match);
   if (res==-1) return -1;
   return res+offset;
}

void main() {
   int pos=0;
   auto text="This interestingly works.";
   // Note the way we can switch between using brackets and not using them.
   doWhile(
     pos=text.find("i", pos),
     pos+1, /// equivalent to pos!=-1, except it also demonstrates
            /// that the conditional can be anything "if" can use.
     { writefln("Hit at ", pos); ++pos; }
   );
}



More information about the Digitalmars-d mailing list