list - 如果原子在列表中则返回 True 的 LISP 函数

标签 list recursion lisp 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))))

最佳答案

您的代码不会返回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/

相关文章:

python - Python列表中第n大项的索引

python - Python 列表中的映射

python - 创建整数列表,添加列表并显示总和

Python 3 压缩列表解包

arrays - 如何在 PostgreSQL 中使用数组作为参数进行递归选择

c# - 为什么我的字典在 C# 中使用复合键时表现不佳?

functional-programming - funcall 的语法糖?

file - 使用 Lisp 从文件中读取矩阵

c - 当递归也使用堆栈时,使用堆栈而不是递归如何在 C 中提供更好的性能?

function - Lisp 中的递归并制作我自己的长度函数