编写一个函数来搜索列表中的匹配项

问题描述 投票:0回答:1

我正在尝试创建一个函数,如果它在另一个列表中找到一个项目的匹配项,它将返回 true。但似乎一切都应该有效,但在调用 (f1 '(2) '(1 2 3)) 时返回 nil

(defun f1 (x y) (条件 ( (等于p x(car y) ) ( t( f1(x(cdr y)) ) ))))

lisp common-lisp
1个回答
0
投票

我在Emacs中自动格式化后的代码如下:

(defun f1 (x y)
  (cond
   ((equalp x(car y))
    (t(f1(x (cdr y)))))))

cond
中有一个子句,所以以
(t ...)
开头的部分实际上是对函数
t
的调用(不存在)。此外,您正在使用
f1
调用
(x (cdr y))
x
也不是函数。

你也在比较

x
(car y)
,但是在你的测试中你传递了两个列表作为参数:

(f1 '(2) '(1 2 3))

我觉得你应该先写一个辅助函数

belongs-to
,它会发现某个
value
是否存在于一个
list
中:

(defun belongs-to (value list)
  "Returns non-NIL if VALUE is found in LIST using EQUALP"
  (cond
    ;; empty list
    (... NIL)
    ;; general case - match head of list
    (... T)
    ;; general case - recurse on tail of list
    (T (belongs-to ... ...))))

拥有此功能后,您可以在

f0
中使用它:

(defun f0 (x y)
  (and x (or (belongs-to ... ...)
             (f0 ... y))))
© www.soinside.com 2019 - 2024. All rights reserved.