list - 像这样 append 两个列表会返回一个列表而不是两个列表的 cons 单元格,这是什么情况?

标签 list append scheme lisp cons

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/

相关文章:

list - 可以让 R5RS 代码与 SchemeUnit 一起工作吗?

scheme - Lisp中最长的元素链

python - 迭代两个不同长度的生成器,其中一个环绕

c - 在 C 中实现和使用动态数组

Python将文件解析为列表列表字典: for loop is only appending last line

python - 更快的 append 值方法

c - C中链表函数的 append (添加到尾部)打印不正确(不打印最后 append 的元素)

lisp - Lisp 中的序列

java - 如何对对象类型列表进行排序

list - 换行符不适用于嵌入消息中的列表 - Discord.py