scheme - `values` 在 Scheme 中是如何工作的?

标签 scheme lisp apply r5rs callcc

来自 R5RS 标准:

Values might be defined as follows:
(define (values . things)
  (call-with-current-continuation
    (lambda (cont) (apply cont things))))

我对此的第一个解释是像 (+ (values 1 2)) 这样的表达式等同于 (apply + '(1 2)) 并且会产生结果 3。但是,根据我的测试,这种解释是不正确的。以下是我对上面代码的解释:values 是一个函数,可以接受任意数量的参数,捆绑到一个名为 things 的列表中。然后,使用列表 things “unbundled”调用当前延续(使用 values 的地方)。

我错过了什么?上面的示例 (+ (values 1 2)) 根据我使用的解释器给出错误或 1。

最佳答案

看,当你打字的时候

(+ (values 1 2))

values 的调用的延续实际上是 + 的单个参数。因此,它要么被视为 1(列表的第一个元素,过程产生的第一个值),要么被视为错误。 R5RS 对此表示:

Except for continuations created by the call-with-values procedure, all continuations take exactly one value. The effect of passing no value or more than one value to continuations that were not created by call-with-values is unspecified.

另一方面,call-with-values 会正确地将列表的元素绑定(bind)到它的 consumer 参数的形式参数:

Calls its producer argument with no values and a continuation that, when passed some values, calls the consumer procedure with those values as arguments.

关于scheme - `values` 在 Scheme 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640332/

相关文章:

list - SICP/Scheme : Procedure that accepts a list of pairs and an element, 返回对列表

numbers - Scheme Lisp 程序求 n 个偶数的和

functional-programming - 创建一个具有可变但固定数量参数的函数

lisp - 如何从文件中读取 sexp

tree - 这真的是广度优先搜索吗

c - 如何使用元循环求值器引导 Lisp 解释器

pandas - 具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()',

syntax - 方案语法转换

python - 如何在 python pandas apply 中定义可变数量的列

javascript - 如何在javascript中将一个div的背景应用到另一个div