About foreach loops
bearophile
bearophileHUGS at lycos.com
Tue Jun 14 23:09:31 PDT 2011
Caligo:
> I think D is fine and you may be confusing index with element.
Unfortunately I think what's confused here is the design of foreach.
> The equivalence of your Python example in D is this:
>
> foreach(e; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]){
Nope, xrange is lazy.
> foreach(e; take(recurrence!("a[n]+1")(0), 10)){
There's std.range.iota for this :-)
> This:
>
> foreach(i; 0..10){
> i += 1;
> write(i, " ");
> }
>
> is the same as this:
>
> for(int i = 0; i < 10; ++i){
> i += 1;
> write(i, " ");
> }
The problem is this equivalence is hidden. foreach() loops look higher level than for loops. So programmers expect this higher level look to be associated with a higher level semantics too. This is why I think currently they are a bit bug-prone. Modifying the loop variable of a foreach loop is code smell, if I see it in code I fix it in some way, using a copy of the loop variable, or I replace the foreach loop with a for loop. So I'd like the compiler to "ignore" or probably better refuse such modifications to the foreach loop variable, if possible.
Bye,
bearophile
More information about the Digitalmars-d
mailing list