【发布时间】:2020-11-13 12:45:03
【问题描述】:
在教程中
Call with current continuation patterns Darrell Ferguson 和 Dwight Deugo,2001 年 9 月
使用call/cc“打破潜在的无限循环”的模式用以下Scheme代码说明(稍作修改,在repl.it中运行并在下面注释):
第 1 部分:“infinitizer”经常在(尾递归)循环内无限运行“action-function”
(define infinitizer
(lambda (action-function)
; "loop" is a closure taking no parameters which calls
; "action-procedure" and then calls "loop".
; After defining it, just call "loop".
(letrec
((loop
(lambda ()
(begin
; ... code to execute before each action would go here ...
(action-function)
; ... code to execute after each action would go here ...
(loop)))))
(loop))))
第 2 部分:这是在顶层调用的函数,例如 (loop-until 4)。它使用receiver 调用call/cc,该infinitizer 围绕计数动作函数 调用,一旦达到停止标准,就会通过调用接收到的延续来打破无限循环:
(define loop-until
(lambda (n)
(let
((receiver
(lambda (exit-function) ; exit-function will be the "current continuation" at call
(let ((count 0)) ; count will be mutated using "set!"
(infinitizer
(lambda () ; this is the action-function
(if (= count n) ; breakoff criterium
(exit-function count) ; call received continuation with exit value
(begin
(display "The count is: ")
(display count)
(newline)
; communicate with the next action-function
; instance by POKE-ing count
(set! count (+ count 1)
))))))))) ; end of receiver definition
(call/cc receiver)))) ; call with the above receiver
例如:
(loop-until 4)
The count is: 0
The count is: 1
The count is: 2
The count is: 3
=> 4
Alternate part 1:似乎(这里的名字infinitizer,原名infinite-loop)函数过于复杂。以下似乎也有效:
(define infinitizer
(lambda (action-function)
(begin
;;; ... code to execute before each action would go here ...
(action-function)
;;; ... code to execute after each action would go here ...
(infinitizer action-function))))
我不知道的两个 infinitizers 之间有什么区别吗?
【问题讨论】:
标签: scheme