]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_62.clj
solutions to 4.38, 4.39 and 4.40
[sicp.git] / src / sicp / ex2_62.clj
1 (ns sicp.ex2_62
2   (:use [clojure.test]))
3
4 (defn union-set [set1 set2]
5   (let [x1 (first set1)
6         x2 (first set2)]
7     (cond (empty? set1) set2
8           (empty? set2) set1
9           (= x1 x2) (cons x1 (union-set (rest set1)
10                                         (rest set2)))
11           (< x1 x2) (cons x1 (union-set (rest set1)
12                                         set2))
13           (> x1 x2) (cons x2 (union-set set1
14                                         (rest set2))))))
15
16 (deftest test-union
17   (are [x y] [= x y]
18        (union-set '() '()) '()
19        (union-set '(1) '()) '(1)
20        (union-set '() '(1)) '(1)
21        (union-set '(1 2 3) '(1 2 3)) '(1 2 3)
22        (union-set '(1 2 3 4) '(1 2 3)) '(1 2 3 4)
23        (union-set '(1 2 4) '(3 4 5)) '(1 2 3 4 5)
24        (union-set '(1 2 3 4) '(5 6 7 8)) '(1 2 3 4 5 6 7 8)
25        (union-set '(1 2 3) '(3 4 5 6)) '(1 2 3 4 5 6)))