To begin in D coming from Python

bearophile bearophileHUGS at lycos.com
Mon Jul 21 09:48:42 PDT 2008


Jarrett Billingsley:
> foreach(ref elem; li)
>     elem *= 2; 

In my first answer I have written some versions of this.
That Python code isn't equivalent to that:

a = [1, 2, 3]
b = a
a = [-el for el in a]
print a, b # [-1, -2, -3] [1, 2, 3]


import std.stdio: putr = writefln;
void main() {
    int[] a = [1, 2, 3];
    auto b = a;

    foreach (ref el; a)
        el = -el;
    putr(a, " ", b); // [-1,-2,-3] [-1,-2,-3]
}



import std.stdio: putr = writefln;
void main() {
    int[] a = [1, 2, 3];
    auto b = a;

    a = a.dup; 
    foreach (ref el; a)
        el = -el;
    putr(a, " ", b); // [-1,-2,-3] [1,2,3]
}

Bye,
bearophile



More information about the Digitalmars-d mailing list