两天前才开始学习Common Lisp,所以请原谅意大利面条代码和不理解。
我的问题如下:我想编写一个函数来执行设置- 操作 A\B,其中 A 和 B 集合不为空。它们由两个列表表示。 到目前为止,我想出了这个:
(defun myDifference (a b)
(if (null a)
(return-from myDifference) ;when a hits NIL, get outta the whole function
)
(if (not(member (car a) b)) ; if the first element of A ist not in B, add it to a list (which later should be the return)
(cons (car a) '())
)
(myDifference (cdr a) b) ; proceed with the remaining elements of A, until (null a) hits
)
我试过:
(myDifference '( 1 2 3) '(1 5 6))
但输出是 NIL,无论我尝试哪个列表。 我怀疑问题出在退出函数上。
最佳答案
您的 my-difference
正文中有 3 个表达式。如果 (null a)
nil
第二个计算 (list a)
或 (list)
,然后丢弃该值。
第三个递归,将 a 更改为 (cdr a)
。
很明显,这 必须返回 nil
,因为最后一个最终递归 a
变为 nil
并且然后递归返回 nil
,因为当您不提供值时,这是默认值。更好的方法是让它成为一个这样的表达式:
(defun my-difference (a b)
(if (null a)
a
(if (not (member (car a) b))
(cons (car a) (my-difference (cdr a) b))
(my-difference (cdr a) b))))
if
的第三部分是 else
部分,如您所见,我们嵌套以获得类似于 if-elseif-else
的内容其他语言。这可以用 cond
写得更平坦:
(defun my-difference (a b)
(cond ((null a) a)
((not (member (car a) b))
(cons (car a) (my-difference (cdr a) b)))
(t (my-difference (cdr a) b))))
关于Common Lisp 中的集合操作 A\B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44238548/