]> git.rkrishnan.org Git - sicp.git/blobdiff - src/sicp/ex1_29.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[sicp.git] / src / sicp / ex1_29.clj
index 33a3458510de28fca4e562689fc777403319a3ed..29cef052061ee687284d967d669aa5e24fdcf057 100644 (file)
@@ -9,20 +9,18 @@
     (+ (term a)
        (sum term (next a) next b))))
 
-(defn make-fac [k n]
-  (cond (= k 0) 1
-       (= k n) 1
-       (even? k) 2
-       :else 4))
-
-(defn simpson-sum [term a next-fn b n k]
-  (let [fac (make-fac k n)]
-    (if (> k n)
-      0
-      (+ (* fac (term a))
-        (simpson-sum term (next-fn a) next-fn b n (+ k 1))))))
-
 (defn simpson-rule [f a b n]
-  (let [h (/ (- b a) n)]
-    (* (simpson-sum f a #(+ h %) b n 0)
-       (/ h 3.0))))
+  (let [h (/ (- b a) n)
+       make-fac (fn [k]
+                  (cond (= k 0) 1
+                        (= k n) 1
+                        (even? k) 2
+                        :else 4))
+       simp-term (fn [k]
+                   (* (make-fac k)
+                      (f (+ a (* k h)))))]
+    (* (/ h 3.0)
+       (sum simp-term 0 inc n))))
+
+;;; lots of great ideas in the above exercise. lexical closures make it easy to
+;;; implement as a and b are constants.
\ No newline at end of file