A suggestion on keyword for_each

Tyler Jameson Little beatgammit at gmail.com
Fri Aug 9 18:16:40 PDT 2013


On Friday, 9 August 2013 at 15:20:38 UTC, Tobias Pankrath wrote:
> On Friday, 9 August 2013 at 14:51:05 UTC, Tyler Jameson Little 
> wrote:
>> Also, I don't particularly like for_reverse, since you can't 
>> use a traditional for-loop syntax with for_reverse:
>>
>>    // would be syntax error
>>    for_reverse (i = 0; i < 5; i++) {}
>
> What do you think would be proper semantics for this?

If the expression is simple enough, it's not out of the question 
for a new programmer to think it will do the same thing as the 
for version, but backwards.

I like foreach and foreach_reverse, because all uses of foreach 
can be foreach_reverse'd (except maybe some ranges), but the same 
does not apply in for. It lacks symmetry, which kind of bothers 
me.

I would prefer a step operator like Python's:

     int[] arr;
     // these two are equivalent
     foreach(x; arr[0 .. $ : -1]) {}
     foreach_reverse(x; arr[0 .. $]) {}

And for ranges:

     auto arr = genRange!int();
     foreach(x; arr.step(-1)) {}

Then I could grab every other one with a step of 2, every third 
with 3, etc. This would not require copying slices or ranges, but 
would be some nice syntax sugar. The index values in the foreach 
would be actual indexes into the slice/range.

If we got this feature, both foreach & foreach_reverse could 
probably be deprecated and merged into for (with no for_reverse). 
This is a pretty substantial change to the language though, so I 
doubt it will make it in.


More information about the Digitalmars-d mailing list