Thursday, April 22, 2010

SICP Series-chapter 2.3.3

At first, I put the code here that provided by text book already.
(defun element-in-set(x set)
 
(cond ((null set) nil)
       
((eq x (car set)) t)
       
(t (element-in-set x (cdr set)))))

(defun adjoin-set(x set)
 
(if (element-in-set x set)
     
set
     
(cons x set)))

(defun intersection-set(set1 set2)
 
(cond ((or (null set1) (null set2)) nil)
       
((element-in-set (car set1))
         
(cons (car set1)
               
(intersection-set (cdr set1) set2)))
       
(t (intersection-set (cdr set1) set2))))
2.59
(defun union-set(set1 set2)
 
(cond ((or (null set1) (null set2)) nil)
       
((null (element-in-set (car set1)))
         
(cons (car set1)
               
(intersection-set (cdr set1) set2)))
       
(t (intersection-set (cdr set1) set2))))

;Another method from Eli.
;Forget to use the function provided by language itself
(defun union-setv2(set1 set2)
 
(append set1 (remove-if (lambda(x)(element-in-set x set2)) set2)))
2.60
(defun union-set-dup(set1 set2)
 
(append set1 set2))

(defun adjoin-set-dup(x set)
 
(cons x set))

(defun element-in-set-dup(x set)
 
(member x set :test #'eq))
2.61
(defun adjoin-set-sort(x set)
 
(cond ((null set) (list x))
       
((= x (car set)) set)
       
((< x (car set)) (cons x set))
       
(t (cons (car set) (adjoin-set-sort x (cdr set))))))
2.62
(defun union-set-sort(set1 set2)
 
(cond ((null set1) set2)
       
((null set2) set2)
       
((= (car set1) (car set2))
         
(cons (car set1) (union-set-sort (cdr set1) (cdr set2))))
       
((< (car set1) (car set2))
         
(cons (car set1) (union-set-sort (cdr set1) set2)))
       
((> (car set1) (car set2))
         
(cons (car set2) (union-set-sort set1 (cdr set2))))))
2.63
Yes,they generate the same list.
2.65
The intersection-set-tree is very similar to the union-set-tree.

(defun union-set-tree(set1 set2) 
    (list-tree (union-set-sort (tree->list set1) (tree->list set2))))
2.66
;key and value are functions to get the key and value from a record.
(defun lookup(key set-of-records)
 
(if (null set-of-records)
     
nil
     
(cond ((= key (key (entry set-of-records))) (value (entry set-of-records)))
           
((< key (key (entry set-of-records)))
             
(lookup key (left-branch set-of-records)))
           
((> key (key (entry set-of-records)))
             
(lookup key (right-branch set-of-records))))))

No comments:

Post a Comment