这本书的答卷是否错误地描述了 Common Lisp 中使用 car/cdr 的多次递归?

问题描述

我正在尝试通过Common Lisp:符号计算的温和介绍这本书来学习 Common Lisp。此外,我正在使用 SBCL、Emacs 和 Slime。

在第 8 章的中间,作者介绍了树上的递归。他在树上用一个函数展示了这个概念,该函数在树的所有非列表元素中插入符号 'q

enter image description here

我在我的环境中做了同样的事情:

(defun atoms-to-q (xs)
  (cond ((null xs) nil)
        ((atom xs) 'q)
        (t (cons (atoms-to-q (car xs))
                 (atoms-to-q (cdr xs))))))

我得到了相同的结果:

CL-USER> (atoms-to-q '(a . b))
(Q . Q)
CL-USER> (atoms-to-q '(hark (harold the angel) sings))
(Q (Q Q Q) Q)

然后书问:

enter image description here

同一本书提供了一个很好的答案表。这显示为这个特定问题的答案:

8.38。如果省略第一个 COND 子句,则 cons 单元链末尾的 NIL 也将转换为 Q。所以 (ATOMS-TO-Q '(A (B) C)) 将返回 (A (B . Q) C . Q)

现在我们到了困惑的地步。在我的环境中,我删除了第一个子句:

(defun atoms-to-q-no-null (xs)
  (cond ((atom xs) 'q)
        (t (cons (atoms-to-q (car xs))
                 (atoms-to-q (cdr xs))))))

在使用书本答题纸上建议的输入运行该函数后,我得到不同的结果

CL-USER> (atoms-to-q-no-null '(a (b) c))
(Q (Q) Q)

解决方法

不幸的是,在应对和 yaking 时,我忘记更改 atoms-to-q-no-null 上的递归调用。我在为 stackoverflow 准备这个问题时意识到了这个错误。

因为我已经写了问题的一部分,所以我认为最好回答它并使努力对其他人有用。

修复函数的递归调用后:

(defun atoms-to-q-no-null (xs)
  (cond ((atom xs) 'q)
        (t (cons (atoms-to-q-no-null (car xs))
                 (atoms-to-q-no-null (cdr xs))))))

我得到了相同的结果:

CL-USER> (atoms-to-q-no-null '(a (b) c))

(Q (Q . Q) Q . Q)

顺便说一句,这是一本非常有趣且写得很好的书。