【问题标题】:Infinite loop while using call-with-current-continuation in Scheme在 Scheme 中使用 call-with-current-continuation 时的无限循环
【发布时间】:2019-03-19 08:42:58
【问题描述】:

我一直在阅读有关call-with-current-continuation 的内容,尤其是在 Scheme 中,并且阅读了许多网站上的各种文章。但是,我仍然不明白在使用call-with-current-continuation 时控制流是如何工作的。

例如,给定下面的附加代码,延续是如何调用的,无论何时调用,控制如何流过这个过程的主体?

 (define call/cc call-with-current-continuation)
 (define showit (lambda (a b) 
                  (begin (display a) (display b) (display " "))))

 (define f
  (lambda (n)
     (let ((p (call/cc (lambda (k) k))))
         (begin
           (showit ’f= n)
          p))))

此外,当使用((f 2) (f 4)) 运行此过程时,它会导致无限循环,其模式如下:

谁能解释一下无限循环背后的原因? 注意:将 Drracket 与 R5RS 一起使用

【问题讨论】:

    标签: scheme infinite-loop continuations callcc


    【解决方案1】:

    Call/cc 返回一个继续周围计算的函数。当它被调用时,控制权将返回到函数的来源处,并赋予函数一个值。

    在示例(let ((p (call/cc (lambda (k) k)))) ...) 中,p 被赋予了一个延续函数。如果 p 被称为 (p 3),则控件将返回到 let 形式,就像它曾经是 (let ((p 3)) ...) 一样。

    ((f 2) (f 4)) 处理 (f 2) 和 (f 4) 的延续,导致无限循环。我试图解释下面的流程:

    => ((f 2) (f 4))
      => (f 2) ;; first (f 2)
           call/cc returns the current continuation (lets say "cc1") into p
           display f=2
           return cc1
    => (cc1 (f 4))
      => (f 4) ;; first (f 4)
           call/cc returns the current continuation cc2 into p
           display f=4
           return cc2
    => (cc1 cc2)
         cc1 goes back to the first (f 2), but call/cc returns now cc2 into p
         display f=2
         returns cc2 from the first (f 2)
    => (cc2 (f 4))
      => (f 4) ;; second (f 4)
           call/cc returns cc3 into p
           display f=4
           return cc3
    => (cc2 cc3)
         cc2 goes back to the first (f 4), but p gets cc3
         display f=4
         returns cc3 from the first (f 4)
    => (cc1 cc3)
         cc1 goes back to the first (f 2), but p gets cc3
         display f=2
         returns cc3 from the first (f 2)
    => (cc3 (f 4))
      => (f 4) ;; third (f 4)
           display f=4
      <= cc4
    => (cc3 cc4)
      => (f 4) ;; second again
           display f=4
      <= cc4
    => (cc2 cc4)
      => (f 4) ;; first again
           display f=4
      <= cc4
    => (cc1 cc4)
      => (f 2) ;; first again
           display f=2
      <= cc4
    => (cc4 (f 4))
      => (f 4) ;; fourth (f 4)
           display f=4
      <= cc5
    ...so on
      
    

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 2014-08-02
      • 2011-04-18
      • 2015-03-27
      • 2017-04-25
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      相关资源
      最近更新 更多