From: Ramakrishnan Muthukrishnan Date: Mon, 7 Jun 2010 11:02:59 +0000 (+0530) Subject: Section 2.1 rational number examples X-Git-Url: https://git.rkrishnan.org/vdrive/%22news.html/module-simplejson._speedups.html?a=commitdiff_plain;h=7bc77809f972dbaf02edd1112938c298b81ca65d;p=sicp.git Section 2.1 rational number examples --- diff --git a/src/sicp/ch2_1.clj b/src/sicp/ch2_1.clj new file mode 100644 index 0000000..9063e98 --- /dev/null +++ b/src/sicp/ch2_1.clj @@ -0,0 +1,43 @@ +(ns sicp.ch2_1 + (:use [sicp utils] + [clojure.contrib test-is])) + +(declare make-rat numer denom) + +(defn add-rat [x y] + (make-rat (+ (* (numer x) (denom y)) + (* (numer y) (denom x))) + (* (denom x) (denom y)))) + +(defn sub-rat [x y] + (make-rat (- (* (numer x) (denom y)) + (* (numer y) (denom x))) + (* (denom x) (denom y)))) + +(defn mul-rat [x y] + (make-rat (* (numer x) (numer y)) + (* (denom x) (denom y)))) + +(defn div-rat [x y] + (make-rat (* (numer x) (denom y)) + (* (numer y) (denom x)))) + +(defn equal-rat? [x y] + (= (* (numer x) (denom y)) + (* (denom x) (numer y)))) + +;; until now, we haven't even defined the data representation. +;; now define make-rat numer and denom. +(defn make-rat [x y] + (let [g (gcd x y)] + (list (/ x g) + (/ y g)))) + +(defn numer [x] + (first x)) + +(defn denom [x] + (first (rest x))) + +(defn print-rat [x] + (println (numer x)"/"(denom x))) \ No newline at end of file