]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_22.clj
Merge branch 'master' of github.com:vu3rdd/sicp
[sicp.git] / src / sicp / ex2_22.clj
1 (ns sicp.ex2_22
2   (:use [sicp [utils :only (square)]]
3         [clojure test]))
4
5 (defn square-list-1 [items]
6   (let [f (fn [things answer]
7             (if (empty? things)
8               answer
9               (recur (rest things) 
10                      (cons (square (first things))
11                            answer))))]
12     (f items nil)))
13
14 (comment
15   "This produced reversed list, as we cons into an empty list and
16    consing into a list always adds elements into the head as this
17    is the most efficient - O(1) - way to add elements into the list."
18 )
19
20 (deftest test-square-list
21   (is (= (square-list-1 '(1 2 3 4)) '(16 9 4 1))))
22
23 ;; Louis then tries to fix his bug by interchanging the arguments to cons:
24
25 (defn square-list-2 [items]
26   (let [f (fn [things answer]
27             (if (empty? things)
28               answer
29               (recur (rest things)
30                      (cons answer
31                            (square (first things))))))]
32     (f items nil)))
33
34 (comment
35   "This won't work because a 'nil' in the cons cell represents the
36    end of the list and cons is used to construct a list by appending
37    elements at the head of the list and not by appending at the tail."
38 )