Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created December 18, 2012 08:53
Show Gist options
  • Save yao2030/4326280 to your computer and use it in GitHub Desktop.
Save yao2030/4326280 to your computer and use it in GitHub Desktop.
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((element-of-set? (car set1) set2)
(union-set (cdr set1) set2))
(else
(cons (car set1) (union-set (cdr set1) set2)))))
;; Sets as unordered lists;
;; do not allow duplicates
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((element-of-set? (car set1) set2)
(union-set (cdr set1) set2))
(else
(cons (car set1) set2)
(union-set (cdr set1) set2))))
;; allow duplicates
(define (adjoin-set x set)
(cons x set))
@yao2030
Copy link
Author

yao2030 commented Dec 18, 2012

two versions of union-set, one is iterative process, the other is recursive

@yao2030
Copy link
Author

yao2030 commented Dec 18, 2012

Duplicate version is preferable when the problem needs more constructing than selecting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment