]> git.rkrishnan.org Git - sicp.git/commitdiff
Solution to 2.35. Yet another enlightening problem
authorRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Tue, 3 Aug 2010 11:08:40 +0000 (16:38 +0530)
committerRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Tue, 3 Aug 2010 11:08:48 +0000 (16:38 +0530)
src/sicp/ex2_35.clj [new file with mode: 0644]

diff --git a/src/sicp/ex2_35.clj b/src/sicp/ex2_35.clj
new file mode 100644 (file)
index 0000000..0bf7f08
--- /dev/null
@@ -0,0 +1,21 @@
+(ns sicp.ex2_35
+  (:use [clojure.test]
+        [sicp [ch2-2 :only (accumulate)]]))
+
+;; Redefine count-leaves from section 2.2.2 as an accumulation:
+
+;; (define (count-leaves t)
+;;   (accumulate <??> <??> (map <??> <??>)))
+(defn count-leaves-with-accumulate [t]
+  (accumulate + 0 (map
+                   (fn [x] (if (seq? x)
+                             (count-leaves-with-accumulate x)
+                             1))
+                   t)))
+
+(deftest test-count-leaves
+  (let [foo (list (list 1 2) 3 4)]
+    (are [x y] [= x y]
+         (count-leaves-with-accumulate foo) 4
+         (count-leaves-with-accumulate (list foo)) 4
+         (count-leaves-with-accumulate (list foo foo)) 8)))
\ No newline at end of file