该函数的目的是使用 lisp 计算列表中 12 的出现次数。
我写的代码:
(defun count12 (x)
(if (null x) 0
(if (and (= 1 (car x)) (= 2 (cadr x)))
(+ 1 (count12 (cdr x)))
(+ 0 (count12 (cdr x)))
)
)
)
使用时出现错误:
Error(s), warning(s): *** - =: NIL is not a number
请注意,我使用的是 Lisp 在线编译器:rextester
。
感谢您的帮助和指导
最佳答案
当您到达列表的最后一个元素时,您将比较 2
和 nil
(nil 的
是 cadr
nil
)。
您需要测试单例列表:
(defun count12 (x)
(if (or (null x) (null (cdr x)))
0
(if (and (= 1 (car x)) (= 2 (cadr x)))
(+ 1 (count12 (cdr x)))
(+ 0 (count12 (cdr x))))))
关于计算列表中出现 1 2 次的 Lisp 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43614140/