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

Bruno Medeiros brunodomedeiros+spam at com.gmail
Wed Jul 18 07:06:10 PDT 2007


downs wrote:
> 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; }
>   );
> }

The usage can also be:

   doWhile(
     pos=text.find("i", pos),
     pos+1,
     (writefln("Hit at ", pos), ++pos )
   );

Only one char less though :P


-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list