]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_5.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[sicp.git] / src / sicp / ex2_5.clj
1 (ns sicp.ex2_5
2   (:use [sicp utils]
3         [clojure.test]))
4
5 (defn my-cons [x y]
6   (* (int (Math/pow 2 x))
7      (int (Math/pow 3 y))))
8
9 (defn- power-of-n* [x n cnt]
10   (let [q (quot x n)
11         r (rem x n)]
12     (if (= r 0)
13       (power-of-n* (quot x n) n (inc cnt))
14       cnt)))
15
16 (defn car [x]
17   (power-of-n* x 2 0))
18
19 (defn cdr [x]
20   (let [p3 (quot x (Math/pow 2 (car x)))]
21     (power-of-n* p3 3 0)))
22
23 (deftest test-car-for-various-cons-cell-values
24   (let [c1 (my-cons 2 3)
25         c2 (my-cons 2 0)
26         c3 (my-cons 0 0)
27         c4 (my-cons 0 1)]
28     (are [p] [= p true]
29          (and (= (car c1) 2)
30               (= (cdr c1) 3))
31          (and (= (car c2) 2)
32               (= (cdr c2) 0))
33          (and (= (car c3) 0)
34               (= (cdr c3) 0))
35          (and (= (car c4) 0)
36               (= (cdr c4) 1)))))
37