我知道 Python 有一些惰性实现,因此,我想知道是否可以在 Python 中使用循环编程。
如果不是,为什么?
我认为您的意思是协同例程,而不是协同递归。是的,这在 Python 中是完全可能的,因为PEP 342: Coroutines via Enhanced Generators已经实现。
典型的例子是消费者装饰器:
def consumer(func):
def wrapper(*args,**kw):
gen = func(*args, **kw)
next(gen)
return gen
wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__
return wrapper
使用这样consumer
的,让我们链接过滤器并通过它们推送信息,充当管道:
from itertools import product
@consumer
def thumbnail_pager(pagesize, thumbsize, destination):
while True:
page = new_image(pagesize)
rows, columns = pagesize / thumbsize
pending = False
try:
for row, column in product(range(rows), range(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生成器和yield表达式;后者让生成器从调用者那里接收信息。
编辑:啊,共同递归确实是一个不同的概念。请注意,Wikipedia 文章使用 python作为示例,此外,还使用了 python generators。
你试过了吗?
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
(尽管这个限制是可配置的)