support for/else and foreach/else
Submitted by Allison (desrt)
Link to original bug (#643645)
Description
Python supports else clauses hanging on the end of its for loops.
The basic idea is that you can write something like this:
for i in some_iterable:
if property(i):
break
else:
print 'Failed to find an item matching property'
return
# use 'i'
There is no other elegant way to write this in the general case without introducing some variable like 'bool found_i' or having the possibility of using a magic value for the 'not-found' case.
Of course, it's just equivalent to this:
for i in some_iterable:
if property(i):
goto found_i
print 'Failed to find an item matching property'
return
found_i:
# use 'i'
but neither Vala nor Python have goto.
We should seriously consider supporting else clauses on our for and foreach loops. If you don't like them then you can just avoid using them. :)
There is only one potential problem that I can imagine. Consider the following code:
if (x != null)
foreach (var i in x) {
...
}
else
...
We now have the usual if/else ambiguity in a place where we didn't have it before. I suggest that we'd deal with this problem by binding the else to the foreach (following the usual convention of binding to the closest one) and issuing a warning about the possible confusion.