About foreach loops
Jesse Phillips
jessekphillips+D at gmail.com
Tue Jun 14 22:11:33 PDT 2011
Nice! I've always expected bearophile's behavior and end up switching to a for loop when wanting to modify the index.
Caligo Wrote:
> I think D is fine and you may be confusing index with element.
>
> The equivalence of your Python example in D is this:
>
> foreach(e; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]){
> e += 1;
> write(e, " ");
> }
>
> or this:
>
> foreach(e; take(recurrence!("a[n]+1")(0), 10)){
> e += 1;
> write(e, " ");
> }
>
> and they both output:
> 1 2 3 4 5 6 7 8 9 10
>
>
>
> 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, " ");
> }
>
> and they both output:
> 1 3 5 7 9
>
>
> This might make it clear:
>
> foreach(i, e; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]){
> i += 1;
> writeln(i, " ", e);
> }
>
> which outputs:
> 1 0
> 3 2
> 5 4
> 7 6
> 9 8
More information about the Digitalmars-d
mailing list