我正在尝试编写一个函数(深度查找),它接受一个列表和另一个参数,如果列表中存在该参数,则返回 T。例如,如果我调用 (deep-find '(A B (C D)) 'C)
它应该返回 true,但是如果我调用 (deep-find '(A B (C D)) 'F)
它应该返回 false。这是我目前的代码,但每次都返回 nil:
(defun deep-find (L n)
(cond
((null L) nil)
((equal n (car L)) t)
((deep-find (cdr L) n))))
最佳答案
您的代码不会返回NIL
每次;它适用于简单的列表。例如 (deep-find '(A B (C D)) 'A)
按原样返回 T
。
cond
中有三种情况:列表结尾、列表头部检查和列表尾部检查。但是,其中没有关于树的内容。因此,如果树中有分支,您需要另一个递归到树的更深层次的条件:
(defun deep-find (L n)
(cond
((null L) nil)
((equal n (car L)) t)
((listp (car L)) ; in case of a branch,
(or (deep-find (car L) n) ; check the branch,
(deep-find (cdr L) n))) ; and check rest of the list
((deep-find (cdr L) n))))
关于list - 如果原子在列表中则返回 True 的 LISP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28424631/