]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_35.clj
Solution to 4.44. A bit too verbose. Can be improved by better
[sicp.git] / src / sicp / ex2_35.clj
1 (ns sicp.ex2_35
2   (:use [clojure.test]
3         [sicp [ch2-2 :only (accumulate)]]))
4
5 ;; Redefine count-leaves from section 2.2.2 as an accumulation:
6
7 ;; (define (count-leaves t)
8 ;;   (accumulate <??> <??> (map <??> <??>)))
9 (defn count-leaves-with-accumulate [t]
10   (accumulate + 0 (map
11                    (fn [x] (if (seq? x)
12                              (count-leaves-with-accumulate x)
13                              1))
14                    t)))
15
16 (deftest test-count-leaves
17   (let [foo (list (list 1 2) 3 4)]
18     (are [x y] [= x y]
19          (count-leaves-with-accumulate foo) 4
20          (count-leaves-with-accumulate (list foo)) 4
21          (count-leaves-with-accumulate (list foo foo)) 8)))