D foreach

Daniel Dittmar daniel.dittmar at sap.corp
Mon Nov 14 05:18:58 EST 2005


bearophileHUGS at lycos.com wrote:
> 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
[...]
> 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.

1. It would be difficult to implement. Python would require the concept 
of 'reference to variable', which has lots of repercussions for 
reference counting, garbage collection etc. Requiring iterators to 
return references would also break all existing iterators. It would also 
be required that the assignment operator is overloadable and this is 
another box of Pandora no one likes to open (well, no one except C++ 
programmemrs).

Or the compiler would have to detect 'assignment to iterator variable' 
and issue an 'update_current' to the iterator.

2. It violates the  Zen of Python 'Explicit is better than implicit' 
(although the definition of 'explict' varies wildly in the Python community)

3. For specific collections like lists and dictionaries, you could write 
a wrapper so that it is possible to write

for ref in wrapper (mycollection):
     print ref.value
     ref.value = newvalue

Daniel



More information about the Python-list mailing list