这个方案代码是什么意思? (使用 lambda 定义 'list' 运算符)

What does this Scheme code mean? (Definition of 'list' operator using lambda)

作为编译列表运算符的定义和returns参数列表,我在this tutorial

找到了这个方案代码
(define list
(lambda args args))

但是,这与我所知道的常用 lambda 语法不匹配。我的意思是,lambda 应该在括号等中包含参数。请解释这是如何工作的。

这定义了一个至少有零个参数的可变参数过程(一个可以接受不同数量参数的过程)。在本例中,所有参数都捆绑到一个名为 args 的列表中。

这是可变参数过程的另一个例子(这个至少需要一个参数),returns 传入的所有参数的最小值:

(define (min arg1 . rest)
  (let loop ((val arg1)
             (rest rest))
    (if (null? rest)
        val
        (let ((next (car rest)))
          (loop (if (< next val) next val)
                (cdr rest))))))

尽管 lambda 中参数的一般形式似乎总是包含括号,但这并不是必需的。如果看一下 this section in the The Scheme Programming Language 4e,它表示:

The general form of lambda is a bit more complicated than the form we saw earlier, in that the formal parameter specification, (var ...), need not be a proper list, or indeed even a list at all. The formal parameter specification can be in any of the following three forms:

  1. a proper list of variables, (var1 ... varn), such as we have already seen,
  2. a single variable, varn, or
  3. an improper list of variables, (var1 ... varn . varr).

In the first case, exactly n actual parameters must be supplied, and each variable is bound to the corresponding actual parameter. In the second, any number of actual parameters is valid; all of the actual parameters are put into a single list and the single variable is bound to this list.

粗体部分(我设置的粗体),是和你的问题很相关的部分。正如您的教程所说,它是一个转换为列表的可变参数参数。

Scheme 解释将形式参数规范与函数调用中提供的实际参数配对,从而进行某种受限模式匹配,形式参数规范作为一种模式。

当它是长度为 n 的适当列表时,这就像是说, 会将每个 n 提供的参数值绑定到规范中的每个变量。 Scheme 要求在这种情况下提供 n 个参数,尽管可以想象某些方言在这种函数调用中允许多于或少于 n 个参数,而不会导致错误:

(define mylist (lambda (x y)      ; (define (mylist x y)    ; exactly two 
  (list x y)))                    ;   (list x y))           ;  arguments required

当它是一个包含 n 个变量和一个尾部变量的不正确列表时,这就像说 如果给定超过 n 个参数,将绑定其余参数,如一个列表,到尾部变量。如果没有更多的参数,自然会一个空列表绑定到尾变量:

(define mylist (lambda (x . y)    ; (define (mylist x . y)  ; at least one
  (cons x y)))                    ;   (cons x y))           ;  argument required

作为形式参数规范的唯一变量被识别为不正确列表的尾变量,作为前一个案例的特定变体。因此它将绑定到函数调用中提供的所有参数值,作为列表:

(define mylist (lambda x          ; (define (mylist . x)    ; any number of
  x))                             ;   x)                    ;  arguments can be used

x 已经是包含所有提供的参数的列表。

很容易看出,所有三种情况都可以通过相同的代码转换来处理,

(define (translate-define-to-lambda code)
  (list (car code)                 ; "define"
        (caadr code)               ; name
        (cons 'lambda
              (cons (cdadr code)   ; parameters
                    (cddr code)))))

(因为(cdr '(<a> . <b>)) == <b>)。