Created
April 23, 2009 18:40
-
-
Save jvantuyl/100676 to your computer and use it in GitHub Desktop.
Proposed Tail-Recursion for Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def do_something(): | |
exited_on_a = False | |
exited_on_b = False | |
exited_on_c = False | |
while 1: | |
... | |
if some_condition: | |
exited_on_a = True | |
break | |
... | |
if some_condition: | |
exited_on_b = True | |
break | |
... | |
if some_condition: | |
exited_on_b = True | |
break | |
... | |
if exited_on_a: | |
... | |
if exited_on_b: | |
... | |
if exited_on_c: | |
... | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def do_something(): | |
... | |
if some_condition: | |
recurse exit_a() | |
... | |
if some_condition: | |
recurse exit_b() | |
... | |
if some_condition: | |
recurse exit_c() | |
... | |
recurse do_something() | |
def exit_a(): | |
... | |
recurse tail() | |
def exit_b(): | |
... | |
recurse tail() | |
def exit_c(): | |
recurse tail() | |
def tail(): | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import tail_recursion | |
from framework import job | |
import framework.message as msg | |
# In this framework, all messages have a response. No data is stored in the | |
# response with the exception of the "init" message, which negotiates a job | |
# id used to associate subsequent results. | |
def new(init_message): | |
j = job(init_message) | |
j.send_and_wait(msg.reply(job.job_id)) | |
allowed = job.authorize() | |
if not allowed: | |
recurse nack(job) | |
job.send_and_wait(msg.ack()) | |
job.start() # This starts a generator stored at job.runner | |
recurse data(job) | |
def data(job): | |
try: | |
next = job.runner.next() | |
job.send(msg.data(next)) | |
recurse data(job.runner.next()) | |
except StopIteration: | |
recurse final(job) | |
except Exception,e: | |
recurse error(job,e): | |
def nack(job): | |
job.send_and_wait(msg.error("not-acknowledged")) | |
def error(job,e = None): | |
job.send(msg.error(e)) | |
recurse job.abort() | |
def final(job): | |
job.wait_on_replies() | |
job.send(msg.final()) | |
recurse job.done() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment