foreach (x; a .. b) and foreach_reverse (x; a .. b) should be disallowed for floats

dsimcha dsimcha at yahoo.com
Mon May 18 07:58:46 PDT 2009


== Quote from Steven Schveighoffer (schveiguy at yahoo.com)'s article
> On Mon, 18 May 2009 09:54:16 -0400, Jacob Carlborg <doob at me.com> wrote:
> > Steven Schveighoffer wrote:
> >> On Sun, 17 May 2009 20:28:24 -0400, Andrei Alexandrescu
> >> <SeeWebsiteForEmail at erdani.org> wrote:
> >>
> >>> Consider:
> >>>
> >>>      foreach (x; 1.0 .. 4.1) writeln(x);
> >>>      foreach_reverse (x; 1.0 .. 4.1) writeln(x);
> >>>
> >>> This sucks. foreach with interval for floating-point types should be
> >>> disallowed.
> >>  foreach_reverse sucks in its own right, while you're looking for stuff
> >> to get rid of, I think it can be done better.
> >>  foreach(x; 4 .. 1 ) should do a reverse interval (and looks way more
> >> readable).
> >> foreach(x; array.reverse) should iterate in reverse.
> >>  for classes, using a method called reverse should work fine:
> >>  foreach(x; myclass.reverse)
> >>  Having to implement opApplyReverse is rediculous, and having a keyword
> >> like foreach_reverse is rediculous.  Reverse isn't the only interesting
> >> iteration pattern, so why focus a whole keyword and syntax on that?
> >>  -Steve
> >
> > I agree with that, but how would you differ foreach(x; array.reverse)
> > from the array.reverse that modifies the array?
> D'oh! I picked the wrong property name.  Forgot about the existing reverse
> property!
> Just to clarify, I am *not* advocating that the propery way to iterate an
> array in reverse is to first reverse the array!
> So pick some other property name:
> foreach(x; array.backwards)
> or whatever.  Too bad reverse is already taken :(
> -Steve

I think what you're looking for is retro() in std.range.  There are a few
problemswith getting rid of foreach_reverse, though:

1.  It would have to stay in D1.  This is not a serious problem, since D2 already
introduces so many breaking changes.

2.  Using retro() would not be a full replacement when it comes to arrays.  For
example, you can't get the indices by doing a

foreach(i, elem; retro(someArray)) {}

3.  As discussed here before, opApply has legitimate uses and is likely not going
anywhere.  In this case, foreach_reverse is the only way to iterate over a range
backwards.

4.  Iteration using the range interface is currently slower than with arrays.  I
posted some benchmarks a while back that were meant to demonstrate something else
but demonstrated this as a side effect.  This is unlikely to matter unless you're
in a very small inner loop, such that the loop overhead is significant compared to
the contents of the loop, but some people with insane performance requirements
might care.



More information about the Digitalmars-d mailing list