附加两个列表的常见且简单的方法如下:
(define (append a b)
(if (null? a)
b
(cons (car a) (append (cdr a) b))))
为什么会这样?当我们到达 a
的最后一个元素时,我显然错误地认为我们将调用 (cons [the original list a, built out of many calls to (cons (car a) ...)] [the original list b])
。简而言之,我不明白为什么函数不返回 (cons a b)
,这将是一个包含两个列表的 cons
单元格。即使我对 a
部分的理解是错误的,为什么将 b
作为整个列表添加到我们的输出中是有效的,而不首先将其分解为单个元素?
我怀疑一个有效的例子对答案很有价值。
答案 0 :(得分:2)
a
无处可告 b
。相反,a
的 elements 被指定为 b
,从 a
的 last 元素开始。考虑:
(append '() '(1 2 3))
--> '(1 2 3) ; there are no elements in `a` to cons onto `b`
(append '(y) '(1 2 3))
--> (cons (car '(y)) (append (cdr '(y)) '(1 2 3)))
--> (cons 'y (append '() '(1 2 3)))
--> (cons 'y '(1 2 3)) ; the last element of `a` is consed onto `b`
--> '(y 1 2 3)
(append '(x y) '(1 2 3))
--> (cons (car '(x y)) (append (cdr '(x y)) '(1 2 3)))
--> (cons 'x (append '(y) '(1 2 3)))
--> (cons 'x (cons (car '(y)) (append (cdr '(y)) '(1 2 3))))
--> (cons 'x (cons 'y (append '() '(1 2 3))))
--> (cons 'x (cons 'y '(1 2 3))) ; the last element of `a` is consed onto `b`
--> (cons 'x '(y 1 2 3)) ; then the next-to-last element of `a`, and so on
--> '(x y 1 2 3)