本文介绍了如何编写使用两个列表并返回四个列表的Scheme函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个元素'(a b c)'(d b f)的列表,想要在一个结果中找到差异,并集和交集.那可能吗?怎么样?

I have 2 lists of elements '(a b c) '(d b f) and want to find differences, union, and intersection in one result. Is that possible? How?

我编写了一个成员函数,用于检查第二个列表中是否有第一个列表中的汽车,但是我不能将成员扔到新列表中.

I wrote a member function that checks if there is a car of the first list in the second list, but I can't throw a member to the new list.

(define (checkResult lis1 lis2)
  (cond...........

))
(checkresult '( a b c) '(d b f))

我的结果应该是(( a c) (d f) (a b c d f) (b)).

推荐答案

就像其他人说的那样,您需要做的就是创建单独的函数来计算两个集合的相交,并集和相减,然后从checkresult中调用它们:

Like others have said, all you need to do is create separate functions to compute the intersection, union, and subtraction of the two sets, and call them from checkresult:

(define (checkresult a b)
  (list (subtract a b)
        (subtract b a)
        (union a b)
        (intersect a b)))

以下是一些联合,交点和减法函数示例:

Here are some example union, intersection, and subtraction functions:

(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)))))

注意:由于这些是集合,顺序无关紧要,因此结果不会排序.此外,这些函数假定输入是集合,因此除了进行合并所需的内容外,不进行任何重复检查.

Note: since these are sets and order doesn't matter, the results are not sorted. Also, the functions assume that the inputs are sets, and therefore don't do any duplicate checking beyond what's required for union.

这篇关于如何编写使用两个列表并返回四个列表的Scheme函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:50