DMD 0.170 release (foreach_reverse)

Bill Baxter dnewsgroup at billbaxter.com
Wed Oct 25 18:45:25 PDT 2006


Walter Bright wrote:

> The saving grace about foreach_reverse is:
> 
> 1) Only a small (5% ?) of loops will be reverse, so you won't see it or 
> need to type it that often.

A good reason why it doesn't deserve its own keyword.

> 2) It's very clear what it does.

And  'foreach(i; list.reversed)' is pretty clear as well.

> 3) It isn't likely to conflict with other names.

Because it's a 15 letter keyword with an underscore!  While we're at it, 
let's make a for_i_equals_one_to_ten keyword, too.  I loop from 1 to 10 
a lot in my code (well, not that much really <5%, but at least it's a 
name that's not likely to conflict with other names).

> 4) It is analogous with C++'s reverse_iterator names.

But those aren't keywords.  And even more analogous is STL's 
std::for_each in the standard header 'algorithm'.
    http://www.sgi.com/tech/stl/for_each.html
Note that STL does not have a std::for_each_reverse.  You get that 
behavior, as you might expect, by using a reverse iterator instead of a 
forward iterator as the argument.


And in another message Walter Bright wrote:

 > foreach_reverse was pretty trivial to implement. All the machinery 
was > already there.

That should be setting off warning bells in your head, too.  "The 
machinery is already there" is just another way of saying "this feature 
is mostly redundant". The foreach machinery already does the job. 
foreach_reverse is more or less just a copy-paste of that code with all 
references to "opApply" replaced with "opApplyReverse".  So of course 
it's trivial to implement.

I'll repeat a line from the "zen of python" one more time, at the risk 
of being told that 'D isn't Python', because I think it's true 
regardless of the language:

   "Special cases aren't special enough to break the rules."

As I understand it, the only real reason for foreach_reverse, when it 
comes down to it, is because of a strong desire to have a special case 
fast reverse iteration for arrays and strings.  But it really should be 
possible to hide that special case from the user and just detect some 
particular property e.g. "some_array.reversed" in a foreach statement. 
It may be a little more work (and maybe you just punt on the 
optimization till 2.0), but in the long run, the language and all it's 
users will benefit from removing that special case.

--bb



More information about the Digitalmars-d-announce mailing list