]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_3.clj
Solutions to 4.27, 4.28 and 4.29.
[sicp.git] / src / sicp / ex2_3.clj
1 (ns sicp.ex2_3
2   (:use [sicp ex2_2 utils]
3         [clojure.test]))
4
5 (declare width-rect height-rect)
6 ;; wishful thinking. Assume that constructors and selectors are
7 ;; available. Now compute perimeter.
8 (defn perimeter-rect [rect]
9   (* 2 (+ (width-rect rect)
10           (height-rect rect))))
11
12 (defn area-rect [rect]
13   (* (width-rect rect)
14      (height-rect rect)))
15
16 ;; now implement the rectangle. One way to represent a rectangle
17 ;; is to use a pair of points representing diagonal corners.
18 (defn make-rect [p1 p2]
19   (list p1 p2))
20
21 (defn p1-rect [r]
22   (first r))
23
24 (defn p2-rect [r]
25   (first (rest r)))
26
27 (defn width-rect [r]
28   (let [p1 (p1-rect r)
29         p2 (p2-rect r)]
30     (abs (- (x-point p1) (x-point p2)))))
31
32 (defn height-rect [r]
33   (let [p1 (p1-rect r)
34         p2 (p2-rect r)]
35     (abs (- (y-point p1) (y-point p2)))))
36
37 (deftest test-rect-perimeter-square
38   (is (= (perimeter-rect (make-rect (make-point 0 0) (make-point 1 1))) 4)))
39
40 (deftest test-rect-area-square
41   (is (= (area-rect (make-rect (make-point 0 0) (make-point 2 2))) 4)))
42
43 ;; part2 - another implementation
44 ;; instead of coordinates, we store height and width itself.
45 (defn make-rect-1 [h w]
46   (list h w))
47
48 (defn width-rect-1 [r]
49   (first r))
50
51 (defn height-rect-1 [r]
52   (first (rest r)))
53
54 ;; the below routines are unmodified versions of the above
55 ;; procedures, but renamed to work around the compiler. Is
56 ;; there a simpler way?
57 (defn perimeter-rect-1 [rect]
58   (* 2 (+ (width-rect-1 rect)
59           (height-rect-1 rect))))
60
61 (defn area-rect-1 [rect]
62   (* (width-rect-1 rect)
63      (height-rect-1 rect)))
64
65 (deftest test-rect-perimeter-square-1
66  (is (= (perimeter-rect-1 (make-rect-1 1 1)) 4)))
67
68 (deftest test-rect-area-square-1
69  (is (= (area-rect-1 (make-rect-1 2 2)) 4)))