Python or Java or maybe PHP?

Alex Martelli aleax at mail.comcast.net
Mon Jan 2 22:49:17 EST 2006


James <fphsml at gmail.com> wrote:

> Now I am curious. How do Python 2.5 and Ruby create new control
> structures? Any code samples or links?

A Ruby example of reimplementing while:

def WHILE(cond)
    |   return if not cond
    |   yield
    |   retry
    | end
i=0; WHILE(i<3) { print i; i+=1 }

Python's a bit less direct here, but:

def WHILE(cond):
    if not cond(): return
    yield None
    yield WHILE(cond)

i = 0
for blah in WHILE(lambda: i<3):
  print i; i += 1

You need to explicitly guard the condition with a lambda to defer
execution (while Ruby's retry repeats deferred execution directly), and
explicitly use recursion to "loop forever", but conceptually the
differences are not all that deep.

Of course nobody would write such WHILE functions in either Ruby or
Python, since the built-in 'while' statement of each language is
perfectly sufficient, but I hope this suffices to show what we mean...


Alex



More information about the Python-list mailing list