Dom*_*ner 4 lisp recursion list common-lisp
我正在尝试编写一个函数(深度查找),它接受一个列表和另一个参数,如果列表中存在该参数,则返回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))))
Run Code Online (Sandbox Code Playgroud)
您的代码不会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))))
Run Code Online (Sandbox Code Playgroud)