Common Lisp 中的集合操作 A\B

标签 set lisp common-lisp

两天前才开始学习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/

相关文章:

Java 8 : mapping list inisde a list

c++ - 如何在 C++ 中实现更好的重新插入到集合中的效率

Haskell - 类似 Lisp 的符号功能

programming-languages - 静态类型的完整 Lisp 变体是否可能?

printing - write、print、pprint、princ 和 prin1 之间有什么区别?

python - 是否可以从 python 中的集合中丢弃数字字符串(仅包含数字的字符串)?

python - 集合中的 union() 和 update() 之间的区别,以及其他?

visual-studio-code - 如何在 Visual Studio Code 上运行 Scheme?

common-lisp - 从 Lisp 列表中删除最后两个元素

common-lisp - 是否为标准Common Lisp函数定义别名?