]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_30.clj
Lazy version of evaluator and tests.
[sicp.git] / src / sicp / ex2_30.clj
1 (ns sicp.ex2_30
2   (:use [clojure.test]))
3
4 ;; without map
5 (defn square-tree [tree]
6   (cond (nil? tree) nil
7         (not (seq? tree)) (* tree tree)
8         :else (cons (square-tree (first tree))
9                     (square-tree (next tree)))))
10
11 (deftest test-sq-tree
12   (are [x y] [= x y]
13        (square-tree '(1 (2 (3 4) 5) (6 7))) '(1 (4 (9 16) 25) (36 49))))
14
15 ;; with map
16 (defn square-tree-with-map [tree]
17   (map (fn [sub-tree]
18          (if (seq? sub-tree)
19            (square-tree-with-map sub-tree)
20            (* sub-tree sub-tree)))
21        tree))
22
23 (deftest test-sq-tree-map
24   (are [x y] [= x y]
25        (square-tree-with-map '(1 (2 (3 4) 5) (6 7))) '(1 (4 (9 16) 25) (36 49))))