Proposal of a general do-while loop [more generic and tested
Taro Kawagishi
tarok at acm.org
Wed Jul 18 02:57:35 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; }
> );
> }
I am new to D, and this is quite impressive.
I guess we can do a similar thing with function objects in C++.
However my original intention was to do simple things in a simple way.
-Taro
More information about the Digitalmars-d
mailing list