my attempt to do the exercises in sicp.

Monday, July 21, 2008

sicp exercise 2.59

;; Exercise 2.59.  Implement the union-set operation for the unordered-list representation of sets.

(define true  #t)
(define false #f)

(define (element-of-set? ele set)
  (cond ((null? set) false)
        ((= (car set) ele) true)
        (else (element-of-set? ele (cdr set)))))

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

(define set1 (list 1 2 3 4))
(define set2 (list 9 8 3 1))
(define set3 (list 9 8 7 6))

(display (union-set set1 set2))(newline)
(display (union-set set1 set3))(newline)
(display (union-set set2 set3))(newline)

No comments: