How to write a scheme function that takes two lists and returns four lists

时光怂恿深爱的人放手 提交于 2019-11-29 08:15:33

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.

Sure it is possible. Assuming that you have function to compute the differences, union intersection etc:

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

Sure it's possible. Here are a couple hints:

  1. what's the result of combining a list and an empty list?
  2. You don't have to do it all at once. Take a piece at a time.

On top of Charlie Martin's and tomjen's answers, I have come up with this source:

Union Intersection and Difference

Implementation of the distinct functions can be found with nice explanations.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!