(:use [sicp utils]
[clojure.contrib test-is]))
+
+;; 2.1.1
(declare make-rat numer denom)
(defn add-rat [x y]
(first (rest x)))
(defn print-rat [x]
- (println (numer x)"/"(denom x)))
\ No newline at end of file
+ (println (numer x)"/"(denom x)))
+
+;;; 2.1.3
+;; scheme/CL cons is nothing but a way to represent a pair.
+(defn s-cons [x y]
+ (fn [m] (cond (= m 0) x
+ (= m 1) y
+ :else (str "argument not 0 or 1 - s-cons"))))
+
+(defn car [z] (z 0))
+
+(defn cdr [z] (z 1))
+
+(def x (s-cons 2 3))
+(car x) ;;=> 2
+(cdr x) ;;=> 3
\ No newline at end of file
(/ 1.0 (lower-bound y)))))
+;; provide new constructors
+(defn make-center-width [c w]
+ (make-interval (- c w) (+ c w)))
+
+(defn center [i]
+ (/ (+ (lower-bound i) (upper-bound i)) 2))
+
+(defn width [i]
+ (/ (- (upper-bound i) (lower-bound i)) 2))
--- /dev/null
+(ns sicp.ex2_12
+ (:use [sicp utils ch2_1_extended ex2_7]
+ [clojure.test]))
+
+(defn make-center-percent [c p]
+ (let [u (+ c (* c p 0.01))
+ l (- c (* c p 0.01))]
+ (make-interval l u)))
+
+(defn percentage [i]
+ (let [c (center i)
+ l (lower-bound i)
+ u (upper-bound i)]
+ (* (/ (- u c) c) 100)))
\ No newline at end of file
--- /dev/null
+(ns sicp.ex2_13
+ (:use [sicp utils ch2_1_extended ex2_7]
+ [clojure.test]))
+(comment
+ "let l1 = c1 - t1,
+ u1 = c1 + t1,
+ l2 = c2 - t2 and
+ u2 = c2 + t2.
+
+Product of two intervals = min (multiples), max (multiples). But since
+t1 and t2 are small, we ignore the t1*t2 terms, so the products
+p1,p2,p3 and p4 are:
+
+ p1 = c1*c2 - c1*t2 - c2*t1
+ p2 = c1*c2 + c1*t2 - c2*t1
+ p3 = c1*c2 - c1*t2 + c2*t1
+ p4 = c1*c2 + c1*t2 + c2*t1
+
+Now, since all numbers are positive, p1 is the min and p4 is the max.
+So, percentage tolerance of the product =
+ (c1t2 + c2t1)/c1c2 * 100
+
+ But t1 = c1 * p1 and t2 = c2 *p2
+
+So, product tolerance is p1 + p2. i.e. sum of individual tolerances."
+)
\ No newline at end of file
(= (cdr c3) 0))
(and (= (car c4) 0)
(= (cdr c4) 1)))))
+
\ No newline at end of file