SICP Exercise 2.59

SICP Exercise 2.59

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

3 Responses to SICP Exercise 2.59

  1. Pawel says:

    I think there should be also condition:


    ((null? set2) set1)

    The procedure would be faster for this case.

  2. Shunu says:

    Yes, I agree with Pawel.

    Here is my code:

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

  3. Bart Gauquie says:

    (define (union-set set1 set2)
    (fold-right adjoin-set set2 set1))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.