我有 2 个元素列表 '(a b c) '(d b f) 并且想在一个结果中找出差异、并集和交集。那可能吗?怎么办?
我写了一个成员函数来检查第二个列表中是否有第一个列表的汽车,但我不能将成员扔到新列表中。
(define (checkResult lis1 lis2)
(cond...........
))
(checkresult '( a b c) '(d b f))
我的结果应该是 (( a c) (d f) (a b c d f) (b))
。
最佳答案
正如其他人所说,您需要做的就是创建单独的函数来计算两个集合的交集、并集和减集,并从 checkresult 中调用它们:
(define (checkresult a b)
(list (subtract a b)
(subtract b a)
(union a b)
(intersect a b)))
以下是并集、交集和减法函数的一些示例:
(define (element? x lst)
(cond ((null? lst) #f)
((eq? x (car lst)) #t)
(#t (element? x (cdr lst)))))
(define (union a b)
(cond ((null? b) a)
((element? (car b) a)
(union a (cdr b)))
(#t (union (cons (car b) a) (cdr b)))))
(define (intersect a b)
(if (null? a) '()
(let ((included (element? (car a) b)))
(if (null? (cdr a))
(if included a '())
(if included
(cons (car a) (intersect (cdr a) b))
(intersect (cdr a) b))))))
(define (subtract a b)
(cond ((null? a) '())
((element? (car a) b)
(subtract (cdr a) b))
(#t (cons (car a) (subtract (cdr a) b)))))
注意:由于这些是集合且顺序无关紧要,因此结果未排序。此外,这些函数假定输入是集合,因此不会进行任何超出并集所需的重复检查。
关于lisp - 如何编写一个接受两个列表并返回四个列表的方案函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/765484/