]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_20.clj
Lazy version of evaluator and tests.
[sicp.git] / src / sicp / ex2_20.clj
1 (ns sicp.ex2_20
2   (:use [clojure test]
3         [sicp utils]))
4 ;; clojure has a slightly different notation compared to Scheme for the
5 ;; arbitraty number of argument notation.
6 (defn same-parity [x & xs]
7   (cons x (filter (fn [y] (if (even? x)
8                             (even? y)
9                             (odd? y)))
10                   xs)))
11
12 ;; another implementation
13 (defn- calc-parity [pred xs result]
14   (if (empty? xs)
15     (reverse result)
16     (let [a (first xs)
17           t (pred a)]
18       (if t
19         (calc-parity pred (rest xs) (cons a result))
20         (calc-parity pred (rest xs) result)))))
21
22 (defn same-parity-2 [x & xs]
23   (if (even? x)
24     (cons x (calc-parity even? xs '()))
25     (cons x (calc-parity odd? xs '()))))
26
27 (defn- calc-parity-3 [pred xs]
28   (if (empty? xs)
29     nil
30     (let [a (first xs)
31           t (pred a)]
32       (if t
33         (cons a (calc-parity-3 pred (rest xs)))
34         (calc-parity-3 pred (rest xs))))))
35
36 (defn same-parity-3 [x & xs]
37   (if (even? x)
38     (cons x (calc-parity-3 even? xs))
39     (cons x (calc-parity-3 odd? xs))))
40
41 (defn same-parity-4 [x & xs]
42   (conj (filter #(if (even? x) (even? %) (odd? %)) xs) x))
43
44 ;; result of the discussion in bang-fp
45 (defn same-parity-5 [x & xs]
46   (cond (nil? xs) (list x)
47         (= (even? x) (even? (first xs))) (cons x (apply same-parity-5 xs))
48         :else (apply same-parity-5 (cons x (rest xs)))))
49
50 (deftest test-same-parity
51   (are [x y] [= x y]
52        (same-parity 1 2 3 4 5 6 7) (list 1 3 5 7)
53        (same-parity 2 3 4 5 6 7) (list 2 4 6)))
54
55 (deftest test-same-parity-2
56   (are [x y] [= x y]
57        (same-parity-2 1 2 3 4 5 6 7) (list 1 3 5 7)
58        (same-parity-2 2 3 4 5 6 7) (list 2 4 6)))
59
60 (deftest test-same-parity-3
61   (are [x y] [= x y]
62        (same-parity-3 1 2 3 4 5 6 7) (list 1 3 5 7)
63        (same-parity-3 2 3 4 5 6 7) (list 2 4 6)))
64
65 (deftest test-same-parity-4
66   (are [x y] [= x y]
67        (same-parity-4 1 2 3 4 5 6 7) (list 1 3 5 7)
68        (same-parity-4 2 3 4 5 6 7) (list 2 4 6)))
69
70 (deftest test-same-parity-5
71   (are [x y] [= x y]
72        (same-parity-5 1 2 3 4 5 6 7) (list 1 3 5 7)
73        (same-parity-5 2 3 4 5 6 7) (list 2 4 6)))