From: Ramakrishnan Muthukrishnan Date: Sat, 27 Mar 2010 19:26:12 +0000 (+0530) Subject: new file for section 1.2 X-Git-Url: https://git.rkrishnan.org/(%5B%5E?a=commitdiff_plain;h=51f7aa601b3641c9d225120c4df1fb292dee145d;p=sicp.git new file for section 1.2 --- diff --git a/chapter1/ch1_2.clj b/chapter1/ch1_2.clj new file mode 100644 index 0000000..6780735 --- /dev/null +++ b/chapter1/ch1_2.clj @@ -0,0 +1,54 @@ +(ns sicp.chapter1.ch1_2 + (:use (clojure.contrib trace))) + + +(defn factorial [n] + (if (= n 1) + 1 + (* n (factorial (- n 1))))) + +;; stack friendly version +(defn factorial2 [n] + (loop [x n acc 1] + (if (= x 1) + acc + (recur (- x 1) (* acc x))))) + +;; even better +(defn factorial3 [n] + (reduce * (range 1 (inc n)))) + +(comment + user> (dotrace [factorial] (factorial 3)) + TRACE t2701: (factorial 3) + TRACE t2702: | (factorial 2) + TRACE t2703: | | (factorial 1) + TRACE t2703: | | => 1 + TRACE t2702: | => 2 + TRACE t2701: => 6 + 6 +) + +(comment + sicp.chapter1.ch1_2> (dotrace [factorial] (factorial 6)) + TRACE t2778: (factorial 6) + TRACE t2779: | (factorial 5) + TRACE t2780: | | (factorial 4) + TRACE t2781: | | | (factorial 3) + TRACE t2782: | | | | (factorial 2) + TRACE t2783: | | | | | (factorial 1) + TRACE t2783: | | | | | => 1 + TRACE t2782: | | | | => 2 + TRACE t2781: | | | => 6 + TRACE t2780: | | => 24 + TRACE t2779: | => 120 + TRACE t2778: => 720 + 720 + ) + +(comment + sicp.chapter1.ch1_2> (dotrace [factorial2] (factorial2 6)) + TRACE t2806: (factorial2 6) + TRACE t2806: => 720 + 720 + ) \ No newline at end of file