]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_29.clj
Lazy version of evaluator and tests.
[sicp.git] / src / sicp / ex1_29.clj
1 (ns sicp.ex1_29
2   (:use [sicp utils]
3         [clojure.contrib trace test-is]))
4
5 ;; simpson's rule of integration
6 (defn sum [term a next b]
7   (if (> a b)
8     0
9     (+ (term a)
10        (sum term (next a) next b))))
11
12 (defn simpson-rule [f a b n]
13   (let [h (/ (- b a) n)
14         make-fac (fn [k]
15                    (cond (= k 0) 1
16                          (= k n) 1
17                          (even? k) 2
18                          :else 4))
19         simp-term (fn [k]
20                     (* (make-fac k)
21                        (f (+ a (* k h)))))]
22     (* (/ h 3.0)
23        (sum simp-term 0 inc n))))
24
25 ;;; lots of great ideas in the above exercise. lexical closures make it easy to
26 ;;; implement as a and b are constants.