Loop-and-a-half (Re: Curious assignment behaviour)
Donn Cave
donn at u.washington.edu
Thu Oct 11 12:55:05 EDT 2001
Quoth Dale Strickland-Clark <dale at riverhall.NOSPAMco.uk>:
...
| The general loop construct as found in C and Java where you have three
| expressions: initialisation, increment/iteration, test is a very
| flexible and powerful approach which I really like.
I sort of regret wasting bandwidth on this purely academic question,
but it's a matter of truly venerable tradition that C's loop is a
bit shy of perfection. The idea as I understand it, is that there
are essentially two control points in a loop, the entry, and the
conditional repeat. C conflates those two in one, because both
entry and the conditional repeat have to be at the "top".
There are plenty of applications for a separate entry, and that's
where we came in. The most frequently cited application for an
assignment expression is
while line = file.readline():
...
A very flexible and powerful approach to looping would allow you
to enter the loop in time to set up for the condition, however many
statements that might take. C and Python give you one expression,
and in C that expression can be an assignment. If you can't do what
you need there, then you have to choose between A) repeat the same
code before the loop:
line = file.readline()
while line:
...
line = file.readline()
or B) take the condition out of the loop control (standard Python solution)
while 1:
line = file.readline()
if not line:
break
People who claim that C fixes this just expose the limitations of
their thinking. C does not fix this, by allowing an assignment
there, except in the restricted case where the pre-conditional
part of the loop can fit into one expression. (Note that I'm not
talking about the initialization section of for(), which is a
pure non-feature - those statements can just as well be written
before the loop.)
Anyone writing a new language should obviously think about that (if
the language has any looping constructs at all - there are so many
"functional" languages crowding the landscape that I'm not sure anyone
invents procedural languages these days.)
Donn Cave, donn at u.washington.edu
More information about the Python-list
mailing list