有人可以解释 Cons 和 Append in scheme 之间的区别吗?

Can someone explain the difference between Cons and Append in scheme?

我都读过它们,它们似乎都构建了一个列表,它们有什么区别?

cons 是所有对的构造函数。

一个正确的列表是 ()(空列表,又名 nil)或一对 cdr 是正确的列表。最后一个具有 () 因为它是 cdr 的任何对链都是一个适当的列表(除了空列表本身)。

虚线列表是一对没有正确列表的列表,因为它是 cdr。因此,最后一个 cdr 不是 () 的一对链与此匹配。

;; dotted lists
(cons 1 2)          ; ==> (1 . 2) 
(cons 1 (cons 2 3)) ; ==> (1 2 . 3) or (1 . (2 . 3))

;; proper lists
(cons 1 '())          ; ==> (1) or (1 . ())
(cons 1 (cons 2 '())) ; ==> (1 2) or (1 . (2 . ()))

append 是一个过程,它使用 cons 创建一个列表,其中包含从左到右的参数列表的所有元素。仅两个列表的 append 的常见实现是:

(define (append lst tail)
  (if (null? lst)
      tail
      (cons (car lst)
            (append (cdr lst)
                    tail))))

append 如果除最后一个参数之外的其中一个参数不是正确的列表,则将失败。 tail 并且可以是任意值:

(append '(1 2 3) '(4 5))       ; ==> (1 2 3 4 5) or (1 . (2 . (3 . (4 . (5 . ())))))
(append '(1 2 3) '(4 5 . 6))   ; ==> (1 2 3 4 5 . 6) or (1 . (2 . (3 . (4 . (5 . 6)))))
(append '(1 2 3) #f)           ; ==> (1 2 3 . #f) or (1 . (2 . (3 . #f)))
(append '(1 2 . 3) '(4 5 . 6)) ; ==> error `car` of number not allowed