我知道Python有一些懒惰的实现,因此,我想知道是否可以在Python中使用循环编程。
如果不是,为什么?
答案 0 :(得分:4)
我认为你的意思是共同惯例,而不是共同递归。是的,它完全可以在Python中使用,因为PEP 342: Coroutines via Enhanced Generators已经实现。
规范示例是消费者装饰者:
def consumer(func):
def wrapper(*args,**kw):
gen = func(*args, **kw)
gen.next()
return gen
wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__
return wrapper
使用这样的consumer
然后让你链接过滤器并通过它们推送信息,充当管道:
@consumer
def thumbnail_pager(pagesize, thumbsize, destination):
while True:
page = new_image(pagesize)
rows, columns = pagesize / thumbsize
pending = False
try:
for row in xrange(rows):
for column in xrange(columns):
thumb = create_thumbnail((yield), thumbsize)
page.write(
thumb, col*thumbsize.x, row*thumbsize.y
)
pending = True
except GeneratorExit:
# close() was called, so flush any pending output
if pending:
destination.send(page)
# then close the downstream consumer, and exit
destination.close()
return
else:
# we finished a page full of thumbnails, so send it
# downstream and keep on looping
destination.send(page)
@consumer
def jpeg_writer(dirname):
fileno = 1
while True:
filename = os.path.join(dirname,"page%04d.jpg" % fileno)
write_jpeg((yield), filename)
fileno += 1
# Put them together to make a function that makes thumbnail
# pages from a list of images and other parameters.
#
def write_thumbnails(pagesize, thumbsize, images, output_dir):
pipeline = thumbnail_pager(
pagesize, thumbsize, jpeg_writer(output_dir)
)
for image in images:
pipeline.send(image)
pipeline.close()
中心原则是python generators和yield expressions;后者允许生成器从调用者接收信息。
编辑:啊,Co-recursion确实是一个不同的概念。请注意,维基百科文章使用python 作为示例,而且使用python 生成器。
答案 1 :(得分:1)
你试过吗?
def a(x):
if x == 1: return
print "a", x
b(x - 1)
def b(x):
if x == 1: return
print "b", x
a(x - 1)
a(10)
作为旁注,python没有尾递归,这对x > 1000
来说会失败(虽然这个限制是可配置的)