我有 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)))))

注意:因为这些都是集和顺序并不重要,结果不排序。此外,该功能假定输入是一组的,因此不做任何重复检查以后有什么需要的结合。

其他提示

当然是可能的。假定有函数来计算的差异,工会路口等:

 (define (checkResult lis1 list2)
   (list (difference lis1 lis2)
        (union ...

确保它是可能的。这里有几个提示:

  1. 什么相结合的结果列表和一个空的名单?
  2. 你没有做到这一切。拿一块的时间。

除了 Charlie Martin 和 tomjen 的回答之外,我还提出了以下来源:

并交集和差集

可以找到不同功能的实现以及很好的解释。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top