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

Steven Schveighoffer schveiguy at yahoo.com
Mon May 18 08:13:15 PDT 2009


On Mon, 18 May 2009 10:58:46 -0400, dsimcha <dsimcha at yahoo.com> wrote:

> 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.

Agreed, not a problem.

> 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)) {}

I'm talking about having a builtin property to arrays that signals it  
should be iterated in reverse, not a library solution.  It can enjoy the  
same benefits of the current foreach_reverse.

As a side note, we need to figure out how to make ranges so they can do  
things like get indices, there has been some discussion on that.  Not  
having indices is going to make interesting ranges hard to use.  For  
example, iterating over a dictionary using a range will have to return  
some kind of key/value pair.

> 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.

Not true.  You can call foreach(x; delegate) to iterate using any delegate  
that has the "opApply" form.  One minor restriction (that I proposed be  
removed, see issue 2443) is that it has to be a delegate, which means that  
you normally have to call it like this:

foreach(x; &obj.inReverse)

> 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.

Again, this is moot because I'm not proposing using library functions,  
they would be builtins (for arrays only of course, user objects still need  
to define an opApply-like function).

However, I think this will be fixed in the future, because range method  
calls should be inlined in the foreach loop (they are probably not  
currently).

And no feature should be discounted because it doesn't perform well today,  
unless you can prove that it's impossible to make it perform well.  I hate  
this mentality some people have about D.

Goes along with the mentality that modules should be small because the  
compiler/linker sucks at trimming unused portions from object files...

-Steve



More information about the Digitalmars-d mailing list