理系学生日記

おまえはいつまで学生気分なのか

問題2-65 (2.3.3 Example: Representing Sets)

順序付き2分木で表現された集合を対象に、\theta (n)のunion-setとintersection-setを定義しろって問題ですけど、2-61、2-63、2-64を組み合わせるとかなり小さくできる予感。tree->list-2が\theta (n)であるかどうかとかの厳密な解析はしてないですけどふいんき(なぜか変換できない)で。


union。

(define (union-ordered-list list1 list2)
  (cond ((null? list1) list2)
	((null? list2) list1)
	(else 
	 (let ((x1 (car list1))
	       (x2 (car list2)))
	   (cond ((< x1 x2) 
		  (cons x1 (union-ordered-list (cdr list1) 
				      list2)))
		 ((= x1 x2)
		  (cons x1 (union-ordered-list (cdr list1)
				      (cdr list2))))
		 (else
		  (cons x2 (union-ordered-list list1
				      (cdr list2)))))))))

(define (union-set set1 set2)
  (let ((set1-list (tree->list-2 set1))
	(set2-list (tree->list-2 set2)))
    (list->tree (union-ordered-list set1-list set2-list))))

intersection。

(define (intersection-ordered-list list1 list2)
  (if (or (null? list1) (null? list2))
      '()
      (let ((x1 (car list1)) (x2 (car list2)))
	(cond ((= x1 x2)
	       (cons x1
		     (intersection-ordered-list (cdr list1)
				       (cdr list2))))
	      ((< x1 x2)
	       (intersection-ordered-list (cdr list1) list2))
	      ((< x2 x1)
	       (intersection-ordered-list list1 (cdr list2)))))))

(define (intersection-set set1 set2)
  (let ((set1-list (tree->list-2 set1))
	(set2-list (tree->list-2 set2)))
    (list->tree (intersection-ordered-list set1-list set2-list))))