如何在方案中建立2套联合

时间:2016-10-18 17:36:33

标签: set scheme racket

(define (element-of-set x lst1)
 (cond ((null? lst1) '())
    ((equal? x (car lst1)) (cons (car lst1) (element-of-set x (cdr lst1))))
    (else
     (element-of-set x (cdr lst1)))))

(define (helper set1 set2) (append set1 set2))

(define (union-set set1 set2)
(cond ((null? set1) '())
    ((> (length (element-of-set (car set1) (helper set1 set2))) 1) (cons (car set1) (union-set (cdr set1) (cdr set2))))
    ((> (length (element-of-set (car set2) (helper set1 set2))) 1) (cons (car set2) (union-set (cdr set1) (cdr set2))))
    (else
     (append (helper set1 set2) (union-set (cdr set1) (cdr set2))))))

此代码假设找到2组的并集。我试着将两组放在一起,然后取出任何重复,但它没有工作。

1 个答案:

答案 0 :(得分:0)

这个怎么样:

#lang racket
(require racket/set)

(define (union-set set1 set2)
  (set-union set1 set2))

(union-set '(1 2 3) '(4 3 2))
=> '(4 1 2 3)

仅供参考,set是Racket中的内置数据类型,因此编写集合联合很容易 - 只需调用现有程序即可!无论如何,如果你想推出自己的版本,它也比你当前的实现更简单,更简单:

(define (element-of-set x lst1)
  (cond ((null? lst1) #f)
        ((equal? x (car lst1)) #t)
        (else (element-of-set x (cdr lst1)))))

(define (union-set set1 set2)
  (cond ((null? set1) set2)
        ((element-of-set (car set1) set2)
         (union-set (cdr set1) set2))
        (else
         (cons (car set1) (union-set (cdr set1) set2)))))