【问题标题】:Is the book answer-sheet wrong about this multiple recursion with car/cdr in Common Lisp?关于 Common Lisp 中 car/cdr 的多重递归,这本书的答题纸错了吗?
【发布时间】:2021-08-18 05:29:06
【问题描述】:

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

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

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

(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)

然后书问:

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

8.38。如果省略第一个 COND 子句,则 cons 单元链末尾的 NIL 也将转换为 Qs。所以 (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)

【问题讨论】:

    标签: tree common-lisp


    【解决方案1】:

    不幸的是,在应对和打闹时,我忘记更改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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多