Empowering foreach with in-place iteration

Janice Caron caron800 at googlemail.com
Sun Sep 9 02:27:54 PDT 2007


There are some things that iterators can do that foreach can't. I
/don't/ want to add iterators to D. Instead, I'd like to see foreach
enhanced, so that it can do the things it currently can't.

Here's my second example.

 string unescape(string s)
 {
     string r;
     for (int i=0; i<s.length; ++i)
     {
         if (s[i] == '\')
         {
             ++i;
             if (i == s.length) break;
             r ~= f(s[i]);
         }
         else
         {
             r ~= s[i];
         }
     }
     return r;
 }

How much nicer it would be to be able to write this as:

 string unescape(string s)
 {
     string r;
     for (char c; s)
     {
         if c == '\')
         {
             iterate(s); /* advances one step through s; modifies c */
             r ~= f(c);
         }
         else
         {
             r ~= c;
         }
     }
     return r;
 }

I'd also like to be able to advance by n steps, not necessarily just
one. That could be done with something like iterate(s,n). For that
matter, I'd also like to go backwards, so it would be great if n could
be negative.

Of course there are some subtleties to consider. What happens if we
reach beyond the end of the array (or the beginning, if we go
backwards)? Is it sufficient to act like break, as in my example
above? Or should that throw an exception? I don't really mind which
behavior is chosen. Either way, I'd still like the feature.



More information about the Digitalmars-d mailing list