From ac34de5a951558b589bfbd713071becebad8ab6c Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan <vu3rdd@gmail.com> Date: Sat, 12 Jun 2010 10:05:11 +0530 Subject: [PATCH] solution to 2.5 --- src/sicp/ex2_5.clj | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/sicp/ex2_5.clj diff --git a/src/sicp/ex2_5.clj b/src/sicp/ex2_5.clj new file mode 100644 index 0000000..95a04c3 --- /dev/null +++ b/src/sicp/ex2_5.clj @@ -0,0 +1,36 @@ +(ns sicp.ex2_5 + (:use [sicp utils] + [clojure.test])) + +(defn my-cons [x y] + (* (int (Math/pow 2 x)) + (int (Math/pow 3 y)))) + +(defn- power-of-n* [x n cnt] + (let [q (quot x n) + r (rem x n)] + (if (= r 0) + (power-of-n* (quot x n) n (inc cnt)) + cnt))) + +(defn car [x] + (power-of-n* x 2 0)) + +(defn cdr [x] + (let [p3 (quot x (Math/pow 2 (car x)))] + (power-of-n* p3 3 0))) + +(deftest test-car-for-various-cons-cell-values + (let [c1 (my-cons 2 3) + c2 (my-cons 2 0) + c3 (my-cons 0 0) + c4 (my-cons 0 1)] + (are [p] [= p true] + (and (= (car c1) 2) + (= (cdr c1) 3)) + (and (= (car c2) 2) + (= (cdr c2) 0)) + (and (= (car c3) 0) + (= (cdr c3) 0)) + (and (= (car c4) 0) + (= (cdr c4) 1))))) -- 2.45.2