]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_39.clj
Lazy version of evaluator and tests.
[sicp.git] / src / sicp / ex2_39.clj
1 (ns sicp.ex2_39
2   (:use [clojure.test]
3         [sicp [ch2-2 :only (accumulate)]
4               [ex2_36 :only (accumulate-n)]
5               [ex2_38 :only (fold-right fold-left)]]))
6
7 ;; Complete the following definitions of reverse (exercise 2.18) in
8 ;; terms of fold-right and fold-left from exercise 2.38:
9
10 ;; (define (reverse sequence)
11 ;;   (fold-right (lambda (x y) <??>) nil sequence))
12 ;; (define (reverse sequence)
13 ;;   (fold-left (lambda (x y) <??>) nil sequence))
14 (defn reverse-with-foldr [sequence]
15   (fold-right (fn [x y]
16                 (concat y (list x)))
17               nil
18               sequence))
19
20 (defn reverse-with-foldl [sequence]
21   (fold-left (fn [x y]
22                (cons y x))
23              nil
24              sequence))
25
26 (deftest test-reverses
27   (let [s1 '(1 2 3 4 5)
28         s2 '(1 2 3 (4 5))]
29     (are [x y] [= x y]
30          (reverse-with-foldr s1) (reverse s1)
31          (reverse-with-foldl s1) (reverse s1)
32          (reverse-with-foldr s2) (reverse s2)
33          (reverse-with-foldl s2) (reverse s2))))