如何解决方案:在条件发出信号后恢复循环
该程序使用Scheme条件并重新启动以循环执行程序10次,并返回程序成功的次数。
这里程序每次 n 是 3 的倍数时都会抛出一个错误。
出于某种原因,第一个错误 (n=3) 被捕获,但循环无法在 n=4 时恢复:
(define (handle! thunk)
(bind-condition-handler
'() (lambda (condition)
(display "resuming...")
(invoke-restart (find-restart 'next)))
thunk))
(let loop((n 1) (count 0))
(display n)(display #\,)
(if (> n 10) count
(handle!
(call/cc
(lambda (cc)
(with-restart
'next "restart here"
(lambda ()
(cc (loop (1+ n) count)))
#f
(lambda ()
(if (= 0 (modulo n 3))
(error n "is multiple of 3!")
(loop (1+ n) (1+ count))))))))))
我未能找到条件示例,并在 the MIT Scheme Reference 之外重新启动。
解决方法
解决方案是将 call/cc 下移到受条件影响的循环参数 'count':
(let loop((n 1) (count 0))
(display n)(display #\,)
(if (> n 10) count
(handle!
(lambda()
(loop (1+ n)
(call/cc
(lambda (cc)
(with-restart
'next "restart here"
(lambda ()
(cc count))
#f
(lambda ()
(if (= 0 (modulo n 3))
(error n "is multiple of 3!"))
(1+ count))))))))))
正确运行:
1 ]=> 1,2,3,resuming...4,5,6,resuming...7,8,9,resuming...10,11,;Value: 7
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。