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))))
This entry was posted on Friday, June 26th, 2009 at 10:38 pm and is filed under Scheme, SICP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
I think there should be also condition:
((null? set2) set1)
The procedure would be faster for this case.
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))))
(define (union-set set1 set2) (fold-right adjoin-set set2 set1))
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
Connecting to %s
Notify me of follow-up comments via email.
[sourcecode language="python"] your code here [/sourcecode]
Get every new post delivered to your Inbox.
I think there should be also condition:
((null? set2) set1)
The procedure would be faster for this case.
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))))
(define (union-set set1 set2)
(fold-right adjoin-set set2 set1))