_indexed_ iteration using opApply or range

Steven Schveighoffer schveiguy at yahoo.com
Mon Dec 13 06:47:39 PST 2010


On Sun, 12 Dec 2010 14:47:04 -0500, spir <denis.spir at gmail.com> wrote:

> Hello,
>
> Had a nice time figuring out how to let opApply allow index iteration  
> like:
>     foreach (i, x ; collection) {}
> Finally managed to do it adding 'i' everywhere:
>
> struct S1 {
>     private int[] elements = [];
>     int opApply (int delegate (ref uint, ref int) block) {
>         foreach (uint i, int n ; this.elements)
>             block(i, n);
>         return 0;
>     }
> }
>
> Is this the intended idiom?
> Now, I'm trying to make this work with ranges instead (input range only  
> as of now). Seems i'm not smart enough to guess it alone...

It's not possible.  There is no mechanism for foreach to use an 'index'  
field from the range.

What's wrong with using opApply?  You should be able to define both range  
primitives and opApply and opApply will be used when foreach is used, and  
the range primitives will be used by things like std.algorithm.

-Steve


More information about the Digitalmars-d-learn mailing list