我想修复我自己的函数,它与默认的交集函数给出相同的结果。我一直在尝试编写一个 lisp 代码,它在两个列表中打印相同的元素。我的代码适用于它。但它不适用于嵌套列表。我怎样才能解决这个问题?
(defun printelems (L1 L2)
(cond
((null L1) nil) ((member (first L1) L2) (cons (first L1) (printelems (rest L1) L2)))
(t (printelems (rest L1) L2))))
预期的输入和输出
(printelems '(2 3 5 7) '( 2 3)) => It works
=> (2 3)
(printelems '(a b '(c f)) '(a d '(c f) e)) => It doesn't work.
=> (a (c f))
编辑
使用默认交集函数可以正常工作。如何在递归函数中使用 equal 函数?
对于默认的路口,
(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
((C F) A)
(intersection '(a b (c f)) '(a d c f e) :test 'equal)
(A)
我的路口,
(printelems '(a b (c f)) '(a d c f e))
(A C F)
(printelems '(a b (c f)) '(a d (c f) e) )
(A C F)
我编辑的代码:
(defun flatten (l)
(cond ((null l) nil)
((atom (car l)) (cons (car l) (flatten (cdr l))))
(t (append (flatten (car l)) (flatten (cdr l))))))
(defun printelemsv1(list1 list2)
(cond
((null list1) nil)
(((member (first list1) list2) (cons (first list1) (printelemsv1 (rest list1) list2)))
(t (printelemsv1 (rest list1) list2)))))
(defun printelems (L1 L2)
(printelemsv1 (flatten L1) (flatten L2)))
最佳答案
Common Lisp 已经有了一个 intersection 功能。如果您想比较像 (C F) 这样的子列表,您需要使用 equal 或 equalp 作为测试参数。
(intersection '(a b '(c f)) '(a d '(c f) e) :test 'equal)
;=> ('(C F) A)
虽然它不会改变 intersection 的工作方式,但您可能真的不想在列表中使用 quote。 Quote 不是列表创建运算符;它是一个“返回读者阅读的任何内容”操作符。读者可以将(a b (c f))读作两个符号的列表和一个子列表,所以(quote (a b (c f))),通常简写为'(a b (c f)) 没问题。例如:
(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
;=> ((C F) A)
关于list - 实现与递归函数相等的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125889/