PEP 315: Enhanced While Loop

SUZUKI Hisao suzuki611 at oki.com
Tue May 13 04:36:31 EDT 2003


In <slrnbbj1vk.21k2.Gareth.McCaughan at g.local>, Gareth McCaughan wrote:
> 
>> And from the mathematical view, "while...else..." is cleanly
>> defined.  Let W be "while e: s else: t".
>> Then W is the least fixed point of the equation:
>>    W = if e:
>>          s; W
>>        else:
>>          t
>> 
>> Imho, both constructs of W. I. Carroll and A. Koenig lack
>> such simplicity.
> 
>     while C1:
>       S1
>     and while C2:
>       S2
>     else:
>       E
> 
> is the least fixed point of
> 
>     W1  ==  if C1: { S1; W2 }
>             else:  E
>     W2  ==  if C2: { S2; W1 }
>             else:  E

Thus,

W1 == if C1:
        S1
        if C2:
           S2
           W1
        else:
           E
      else:
        E

> But I'm not sure why this is important, since (1) neither
> of these deals with "break" and "continue" and (2) maybe
> 0.001% of Python programmers think of their programs as
> built out of least fixed points of sets of equations.

Yes, many ones do not think of fixed points, but I hope you
will understand the core point easily.  Well, you can see the
equation just a "macro" definition ;-).  Frankly speaking,
"least" just means that the interpreter executes only what
written in the given program.

The important point is that you can see the (non-)simplicity
of the given construct from its equation (read 'macro') clearly.

Given the equation, you can now see the secret of the "else"
clause of "while" statement of Python, which seems very
unique :-)  It corresponds that of "if" plainly.  I believe
the naturalness of the "while..else.." comes from this.

"and while" lacks such simple correspondence and has
multiple occurrences of E (statements in "else" clause).

And you may think of a looping construct which is described
as a recursive "if..elif..".  For example,

while C1:
   S1
or while C2:
   S2
or while C3:
   S3
else:
   E

whose meaning is given by

W = if C1:
      S1; W
    elif C2:
      S2; W
    elif C3:
      S3; W
    else:
       E

Note that it is not my invention.  If I remember correctly,
Concurrent Pascal had such a construct.
Though I doubt its actual usefulness, it is so natural
that some may mistake the meaning of "and while" for it ;-)

Thus I want a plain "loop", if we have to fix the looping
constructs of Python.

BTW, as for "break" and "continue", I think there are two
approaches.
A: unfold the equation, and reduce it to "if..else..".
B: use "try..raise..except.." construct.
If I remember correctly, the Modula-3 report takes the
approach B to describe its BREAK statement.

-- SUZUKI Hisao






More information about the Python-list mailing list