我是LISP的初学者所以我需要编写一个函数(DUPLICATE-ELEMENTS L)
,它检查L中元素(原子或列表)的重复出现。
示例:
(DUPLICATE-ELEMENTS '(a b a c)) -> T
(DUPLICATE-ELEMENTS '(a b (a b)) -> NIL
(DUPLICATE-ELEMENTS '(a b (a b) c d (a b))) -> T
我找到了检查唯一
的函数(defun Unique (l)
(or (null l)
(and (not (member (car l) (cdr l)))
(Unique (cdr l)))))
但我需要像示例中那样反之亦然。请你帮助我好吗。
当我运行这个
(Unique '(a b a c))
我收到NIL
,但我需要收到T
答案 0 :(得分:0)
也许你需要这样的东西:
(defun unique (data-list)
(or (null data-list)
(and (not (member (car data-list) (cdr data-list) :test #'equalp))
(unique (cdr data-list)))))
(defun duplicate-elements (data-list)
(not (unique data-list)))
?您还可以声明谓词,以便将您的函数作为参数进行比较。为什么在等待DUPLICATE-ELEMENTS
时,您认为nil
会返回T
?我认为这是因为member
用于比较某些默认谓词的值。也许它是eq
,它不用于列表比较。见这个例子:
(defun unique (data-list &key (test #'eq))
(or (null data-list)
(and (not (member (car data-list) (cdr data-list) :test test))
(unique (cdr data-list)))))
(defun duplicate-elements (data-list &key (test #'eq))
(not (unique data-list :test test)))
以及如何使用它们来获得正确的结果:
CL-USER> (duplicate-elements '((a b) a c (a b)))
NIL
CL-USER> (duplicate-elements '((a b) a c (a b)) :test #'equalp)
T