sicp每日一題[2.60]

再思即可發表於2024-10-28

Exercise2.60

We specified that a set would be represented as a list with no duplicates. Now suppose we allow duplicates. For instance, the set {1, 2, 3} could be represented as the list (2 3 2 1 3 2 2). Design procedures element of-set?, adjoin-set, union-set, and intersection-set that operate on this representation. How does the efficiency of each compare with the corresponding procedure for the non-duplicate representation? Are there applications for which you would use this representation in preference to the nonduplicate one?


這道題目我有點沒理解,如果允許重複的話,交集該怎麼處理?所以最後交集我沒有改變,element-of-set? 也沒有修改。

(define (element-of-set? x set)
  (cond ((null? set) false)
        ((equal? x (car set)) true)
        (else (element-of-set? x (cdr set)))))

(define (adjoin-set x set)
  (cons x set))

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

(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 set1 (list 1 3 5 'a 'b 'c))
(define set2 (list 2 4 6 'a 'd 'c))

(adjoin-set 'a set1)
(union-set set1 set2)
(intersection-set set1 set2)

; 執行結果
'{a 1 3 5 a b c}
'{1 3 5 a b c 2 4 6 a d c}
'{a c}

相關文章