call-with-current-continuation 只能用 lambda 和闭包来实现吗?

发布于 2024-09-25 08:43:04 字数 162 浏览 1 评论 0原文

有谁知道 call/cc 是否可以只用 lambda 和闭包来实现?

看起来 call/cc 会中断程序的流程(就像异常一样),但 lambda 和闭包无法做到这一点。因此我认为 call/cc 不能通过 lambda 和闭包来实现。

还有更多想法吗?

Does anyone know if call/cc can be implemented with just lambdas and closures?

It seems that call/cc interrupts the program's flow (like an exception) but lambdas and closures can't do that. Therefore I think call/cc can't be implemented via lambdas and closures.

Any more ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕梦 2024-10-02 08:43:05

这个问题不是特别清楚,因为“仅使用 lambda 和闭包实现”到底是什么意思?

无论如何,通过以延续传递风格手动编写,可以在任何带有闭包的语言中使用延续。然后可以通过扩展编译器来实现这种形式的自动翻译,Lisps 通常允许通过宏在用户级别上实现这一点。例如,请参阅 cl-cont,这是一个为 Common Lisp 实现延续的库,它是 像Scheme这样的

高效普遍延续很可能在直接处理程序堆栈的较低级别上实现,但这不是要求,只是一种优化。

The question is not particularly clear, since what exactly does "implemented with just lambdas and closures" mean?

In any case, continuations can be used in any language with closures by manually writing in continuation passing style. Then automatic translation into this form can be implemented by extending the compiler, which Lisps typically allow on user level through macros. For example see cl-cont, a library implementing continuations for Common Lisp, which is a language that doesn't have them built in.

Efficient pervasive continuations like in Scheme are likely to be implemented on a lower level directly dealing with the program stack, but this is not a requirement, just an optimization.

忘东忘西忘不掉你 2024-10-02 08:43:05

在Scheme中,当转换为连续传递样式(CPS)时,您可以使用lambda来实现call/cc。转换为 CPS 时,每次出现的 call/cc 都可以替换为以下等价内容:

(lambda (f k) (f (lambda (v k0) (k v)) k))

其中 k 是要保存的延续,而 (lambda (v k0) (kv)) 是恢复此延续的转义过程(无论调用时处于活动状态的任何延续k0,都会被丢弃)。

所以,回答你对Scheme的问题:是的,可以做到。

In Scheme you can implement call/cc using lambdas when converting to continuation passing style (CPS). When converting into CPS, every occurrence of call/cc can be replaced with the following equivalent:

(lambda (f k) (f (lambda (v k0) (k v)) k))

where k is the continuation to be saved, and (lambda (v k0) (k v)) is the escape procedure that restores this continuation (whatever continuation k0 that is active when it is called, is discarded).

So, to answer your question for Scheme: yes, it can be done.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文