Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #110787 > unrolled thread

Re: "for/while ... break(by any means) ... else" make sense?

Started byTerry Reedy <tjreedy@udel.edu>
First post2016-06-29 16:22 -0400
Last post2016-06-29 16:22 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: "for/while ... break(by any means) ... else" make sense? Terry Reedy <tjreedy@udel.edu> - 2016-06-29 16:22 -0400

#110787 — Re: "for/while ... break(by any means) ... else" make sense?

FromTerry Reedy <tjreedy@udel.edu>
Date2016-06-29 16:22 -0400
SubjectRe: "for/while ... break(by any means) ... else" make sense?
Message-ID<mailman.115.1467231752.2358.python-list@python.org>
On 6/29/2016 6:01 AM, Victor Savu wrote:
> There are many posts trying to explain the else after for or while.

My take: a while statement *is* a repeated if statement, and that is how 
it is implemented.

while condition:
     true()

is equivalent to and implemented in machine language without a native 
while command as

<label> if condition:
    true()
    goto label

An else clause is executed exactly when the condition is false.

This understanding is useful in understanding how and why tail recursion 
is equivalent to and can be converted to a while loop.

def f(n, accum):
     if recurse:
         return f(g(n), h(n, accum))
     else:
         return accum

What does the recursive call do?  It assigns new values to the 
parameters and goes to the top of the code.  Since it is a tail call, 
the old parameter bindings are not needed.  So the above does the same as

def f(n, accum):
     <label> if recurse:
         n, accum = g(n), h(n, accum
         goto label
     else:
         return accum

which is the same, by the above, as

def f(n, accum):
     while recurse:
         n, accum = g(n), h(n, accum
     else:
         return accum

In other words, convert properly formatted tail recursion (where the 
condition is the recurse condition, rather than the terminate condition) 
by replacing 'if' with 'while' and the tail recursive call with 
unpacking assignment.

It is conventional to drop the else:, but it is implicitly still there.

-- 
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web