Can call-with-current-continuation be implemented only with lambdas and closures?

我们两清 提交于 2019-12-30 00:32:22

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3811448/can-call-with-current-continuation-be-implemented-only-with-lambdas-and-closures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!