Python的延续与Ruby的等价物
Ruby中以下代码的Python等价物是什么?Python的延续与Ruby的等价物
def loop
cont=nil
for i in 1..4
puts i
callcc {|continuation| cont=continuation} if i==2
end
return cont
end
> c=loop
1
2
3
4
> c.call
3
4
参考:Secrets of lightweight development success, Part 9: Continuations-based frameworks
看看在yield语句来使发电机。
我不会说任何红宝石,但好像你正在寻找这样的:
def loop():
for i in xrange(1,5):
print i
if i == 2:
yield
for i in loop():
print "pass"
编辑:我意识到这是基本真实的延续的一个特例,但它应该是足以满足大多数目的。使用yield
将生成器上的继续和.next()
消息返回(仅通过调用loop()
返回)以重新输入消息。
def loop():
def f(i, cont=[None]):
for i in range(i, 5):
print i
if i == 2:
cont[0] = lambda i=i+1: f(i)
return cont[0]
return f(1)
if __name__ == '__main__':
c = loop()
c()
使用generator_tools
(安装: '$ easy_install generator_tools
'):
from generator_tools import copy_generator
def _callg(generator, generator_copy=None):
for _ in generator: # run to the end
pass
if generator_copy is not None:
return lambda: _callg(copy_generator(generator_copy))
def loop(c):
c.next() # advance to yield's expression
return _callg(c, copy_generator(c))
if __name__ == '__main__':
def loop_gen():
i = 1
while i <= 4:
print i
if i == 2:
yield
i += 1
c = loop(loop_gen())
print("c:", c)
for _ in range(2):
print("c():", c())
输出:
1
2
3
4
('c:', <function <lambda> at 0x00A9AC70>)
3
4
('c():', None)
3
4
('c():', None)
generator_tools在它可以复制的内容上相当有限,请参阅其文档。我不会提名generator_tools作为callcc的替代品。 – pts 2010-12-01 19:56:43
有很多薄弱的解决方法,其工作在特殊情况下(看其他的答案,这样问题),但是没有Python语言结构,它相当于callcc
或者可以用于构建等同于的东西。
你可能想尝试Stackless Python或greenlet Python扩展,两者都提供协同程序,在此基础上,可以建立一次性continutations,但是这仍然比Ruby的callcc
(它提供了完整的延续)弱。
这不是那么容易,请参阅http://*.com/questions/312794/#313073 – jfs 2008-11-23 23:08:41