为什么延续传球风格 [英] Why continuation passing style

查看:81
本文介绍了为什么延续传球风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scheme Programming Language 中,Kent Dybvig(第 4 版)第 3.4 节,他非常清楚地描述了什么继续传递风格是.对于为什么,他给出了两个原因:

In The Scheme Programming Language by Kent Dybvig (4th edition) section 3.4, he describes very clearly what continuation passing style is. For the why he gives two reasons:

  1. 将多个结果传递给它的延续,因为实现延续的过程可以接受任意数量的参数.
  2. CPS 还允许过程采用单独的延续 ...,它可以接受不同数量的参数.

由于第一个原因也可以使用 values 过程完成,第二个原因使用 case-lambda,所以我不清楚使用连续传递样式的优势.有人可以向我展示一些示例,说明哪些地方适合继续传递风格,哪些地方可以使代码更好、更清晰等?

Since the first reason can also be done using the values procedure and the second using case-lambda, I'm not clear the advantages of using continuation passing style. Could someone show me some examples of where continuation passing style is appropriate, where it makes the code better, clearer, etc.?

推荐答案

Dybvig 使用本节中的显式延续来激励将 call/cc 作为语言的一部分.当他提到编写没有它的代码需要对所有使用的代码(包括您调用的函数)进行全局转换时,在本节末尾附近提出了要点.因此,在 Scheme 中,您通常使用宏构建自己的构造,而延续是这些有用的构造之一——但您无法通过宏实现它们,因为它们仅实现局部转换.

Dybvig uses the explicit continuations in this section to motivate having call/cc as part of the language. The main point is made near the end of the section when he mentions that writing code without it requires a global tranformation of all code that is used, including functions that you call. So in Scheme you usually build your own construct using macros, and continuations are one of these useful constructs -- but you cannot implement them via macros since they implement only local transformations.

但是直接使用 CPS 样式仍然很有用:例如,正如他提到的,您可以编写一个具有多个延续的函数,可能具有不同的参数——就像一个接收单输入函数的解析函数将解析值发送到并在解析失败时调用 nullary 失败函数(并且此函数可能会因错误或回溯而中止并尝试使用其他解析规则).另一个可能的用途是当您想要准确控制进入延续的内容而不是让 call/cc 获取完整上下文时.

But using a CPS style directly can still be useful: for example, as he mentions, you could write a function that has more than one continuation, possibly with different arrities -- like a parsing function that receives a single-input function to send a parses value to and a nullary failure function to call when parsing fail (and this function might abort with an error or backtrack and try using other parsing rules). Another possible use is when you want to control exactly what goes into the continuation rather than letting call/cc grab the full context.

还有一个明显的例子是用没有一流延续的语言编写代码,使 CPSed 代码成为您唯一的选择.一个例子是许多使用 IO 的 node.js 程序,并且几乎迫使您使用显式 CPS 编写代码.

There also the obvious case of writing code in a language that has no first-class continuation, making CPSed code your only choice. An example of that would be lots of node.js programs that use IO and pretty much force you to write code in explicit CPS.

这篇关于为什么延续传球风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆