D foreach

B

bearophileHUGS

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

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 = p;

Is equal to Python:
for i,p in enumerate(v2): v1 = 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
 
D

Daniel Dittmar

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 [...]
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,227
Latest member
Daniella65

Latest Threads

Top