D foreach

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sun Nov 13 13:01:00 EST 2005


The Digital Mars D compiler is a kind of "improved c++", it contains a
"foreach" statement:
http://www.digitalmars.com/d/statement.html#foreach

Usage example:
foreach(int i, inout int p; v1) p = i;

Is equal to Python:
for i in xrange(len(v)): v[i] = i

That is: v1 = range(len(v1))
(Some people use something like this in Python to scan a list of lists,
so p become a reference to a list, that can be modified in place, but
it's not much explicit way of doing things.)


Another example:
foreach(int i, int p; v2) v1[i] = p;

Is equal to Python:
for i,p in enumerate(v2): v1[i] = p

So the variable p contains (scans) the elements of the given iterable
object, but if you assign p with a value, that value becomes copied
inside the mutable iterable too. Those are little examples, but I think
it can be quite useful in more complex code.

Bye,
bearophile




More information about the Python-list mailing list