append 两个列表的常见且简单的方法如下:
(define (append a b)
(if (null? a)
b
(cons (car a) (append (cdr a) b))))
为什么这有效?当我们到达 a
的最后一个元素时,我明显错误地认为我们将调用 (cons [原始列表 a,由对 (cons (car a) 的多次调用构建而成)。 ..)] [原始列表b])
。简而言之,我不明白为什么函数不返回 (cons a b)
,这将是一个包含两个列表的 cons
单元格。即使我对 a
部分的理解是错误的,为什么将 b
作为整个列表添加到我们的输出中是有效的,而不首先将其分解为各个元素?
我怀疑一个有效的示例对于答案非常有值(value)。
最佳答案
a
没有任何地方可以与 b
结合。相反,a
的元素被转换为b
,从a<的最后元素开始
。考虑:
(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)
关于list - 像这样 append 两个列表会返回一个列表而不是两个列表的 cons 单元格,这是什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65863920/