From: Ramakrishnan Muthukrishnan Date: Thu, 22 Jul 2010 19:52:14 +0000 (+0530) Subject: solution to 2.30 X-Git-Url: https://git.rkrishnan.org/%5B/frontends/flags/%22news.html/nxhtml.html?a=commitdiff_plain;h=aa6eaa6ab06560d043d30f9c0f5fd823afa6b56c;p=sicp.git solution to 2.30 --- diff --git a/src/sicp/ex2_30.clj b/src/sicp/ex2_30.clj new file mode 100644 index 0000000..e79f06b --- /dev/null +++ b/src/sicp/ex2_30.clj @@ -0,0 +1,25 @@ +(ns sicp.ex2_30 + (:use [clojure.test])) + +;; without map +(defn square-tree [tree] + (cond (nil? tree) nil + (not (seq? tree)) (* tree tree) + :else (cons (square-tree (first tree)) + (square-tree (next tree))))) + +(deftest test-sq-tree + (are [x y] [= x y] + (square-tree '(1 (2 (3 4) 5) (6 7))) '(1 (4 (9 16) 25) (36 49)))) + +;; with map +(defn square-tree-with-map [tree] + (map (fn [sub-tree] + (if (seq? sub-tree) + (square-tree-with-map sub-tree) + (* sub-tree sub-tree))) + tree)) + +(deftest test-sq-tree-map + (are [x y] [= x y] + (square-tree-with-map '(1 (2 (3 4) 5) (6 7))) '(1 (4 (9 16) 25) (36 49))))