No, loop-and-a-half! (Re: REPEAT... UNTIL ?)

Alexis Layton alexis.layton at post.harvard.edu
Thu Jul 11 22:43:50 EDT 2002


In article <3D24FAC5.3050406 at something.invalid>, Greg Ewing
<see_reply_address at something.invalid> wrote:

> On the other hand, a situation that *is* very common is
> a loop-and-a-half, with the exit condition in the middle.
> So far, I've never seen *any* really good loop-and-a-half
> structure in any language, and I think Python has a chance
> to be truly innovative here.
> 
> The syntax I favour at the moment for Python looks like
> 
>    while:
>      line = f.readline()
>    gives line <> "":
>      do_something()
> 
> Some day I'll get around to PEPping this...

The syntax I've always liked comes from an old SIGPLAN Notices
submission, which I am unable to locate right now, and therefore
cannot attribute.  Of course, it was for a Algol-ish/Pascal-ish
language, and adapting it to Python runs into a little trouble.

Please not that no attempt has been made to conserve reserved
words.  This is a theoretical excercise.

It goes along the lines of

   loop:
      <stmts>
      exit when <cond>        ALTERNATIVE: when <cond> exit
      <stmts>
      when <cond>:
         <stmts>
         exit
      <stmts>
      ...

Pseudo BNF: (note does not handle suite one-liners)

LoopStmt ->    "loop" ":" INDENT LoopSuite DEDENT

LoopSuite  ->  Statement
               |     ExitWhenClause
               |     WhenClause

ExitWhenClause ->    "exit" "when" Condition

WhenClause  ->    "when" Condition ":" INDENT ExitSuite DEDENT

ExitSuite   ->    Statements* ExitStatement

ExitStatement -> "exit"

Any attempt to move the "when" clauses out to the "loop" level of
indentation runs into the problem of continuing the loop after the
exit:

loop:
   unconditional-stmts
when <cond>:
   cleanup-stmts
   exit
<<where do we put the next unconditional statement?>>

If we don't allow cleanup, we could do

loop:
   stmts
exit when <cond>
   stmts
...

which is certainly simpler but less practical. It has the "distinction"
of having indentation following a non-":" statement.  This just
looks wrong to me, but in any exit-in-the-middle construct you
have this problem.

Note that there is no reason that exit/when clauses could not also
apply to for and while loops.

The principal advantages of exit/when clauses is that they are lexical
constructs tied to the loop itself, rather than arbitrarily deeply
constructed if-elif-else statements with break/continue statements.

loop:
   thing = getAThing()
   exit when not thing
   thing.process()

-- 
Alexis Layton
alexis . layton @ post . harvard . edu



More information about the Python-list mailing list