代码之家  ›  专栏  ›  技术社区  ›  bhadra

python等价于ruby的continuations

  •  7
  • bhadra  · 技术社区  · 16 年前

    在Ruby中,以下代码的python等价物是什么?

    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

    5 回复  |  直到 14 年前
        1
  •  5
  •   Greg Hewgill    16 年前

    你引用的文章包含一个链接 Continuations Made Simple And Illustrated 在参考资料部分,它讨论了Python语言中的延续。

        2
  •  2
  •   user40098    16 年前

    看看 yield 生成生成器的语句。

    我不会说红宝石,但你好像在找这个:

    def loop():
        for i in xrange(1,5):
            print i
            if i == 2:
                yield
    
    
    for i in loop():
        print "pass"
    

    编辑:我认识到这基本上是一个真正的连续性的专门化,但是对于大多数目的来说,它应该是足够的。使用 yield 返回延续和 .next() 发电机上的消息(通过调用返回 loop() 重新进入。

        3
  •  2
  •   jfs    16 年前

    使用 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)
    
        4
  •  2
  •   pts    14 年前

    在特殊情况下,有许多薄弱的解决方法(请参阅此问题的其他答案),但没有与 callcc 或者可以用来建造相当于 来电显示 .

    你可能想试试 Stackless Python greenlet python扩展,这两个扩展都提供协程,基于协程可以构建一次连续性,但这仍然比ruby的弱 来电显示 (提供完整的延续)。

        5
  •  0
  •   jfs    16 年前
    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()