lisp - 如何编写一个接受两个列表并返回四个列表的方案函数

标签 lisp scheme racket

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

相关文章:

lisp - 如何对所有形状仅使用一个移动功能

python-2.7 - 将 Python 翻译成 Scheme/Racket

clojure - 惯用的方式使用 for,同时仍然保持高性能

LISP 练习秘诀

scheme - “continuation prompt?”到底是什么

scheme - 访问 Scheme 和 Racket 中的结构子类型字段

macros - Racket - 使用宏实现 let* 函数

Racket中的动态函数调用;或从字符串中获取过程

scheme - 替换(可能嵌套的)列表中第一次出现的符号

functional-programming - 为什么define-syntax of or in scheme需要考虑三个条件?