]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_44.clj
solutions to 4.35, 4.36 and 4.37
[sicp.git] / src / sicp / ex1_44.clj
1 (ns sicp.ex1_44
2   (:use [clojure.contrib test-is]
3         [sicp utils]
4         [sicp ch1_3]
5         [sicp ex1_43]))
6
7 (def dx1 0.00001)
8
9 (defn smooth [f]
10   (fn [x]
11     (average (f (- x dx1))
12              (f x)
13              (f (+ x dx1)))))
14
15 ;; smooth takes a function as argument. repeated takes a function
16 ;; which needs to be repeated. Here it is the smooth function and
17 ;; the number of times it needs to be repeated. We call the function
18 ;; returned by repeated with f.
19 (defn smooth-repeatedly [f n]
20   ((repeated smooth n) f))
21
22 ;; borrowing an idea from Drew Hess' solutions, we generate a test impulse
23 ;; function
24 (defn impulse-maker [x a]
25   (fn [y] (if (= y x)
26             a
27             0)))
28
29 ;; we define a function which has an impulse at x=2 with a value 10.
30 (defn my-impulse-func [x]
31   ((impulse-maker 2 10) x))
32
33 (comment
34 ((smooth my-impulse-func) 2)
35 ;;=> 3.3333333
36 user> ((smooth my-impulse-func) 1)
37 ;;=> 0.0
38 user> ((smooth (smooth my-impulse-func)) 2)
39 ;;=> 3.3333333
40 user> ((smooth (smooth (smooth my-impulse-func))) 2)
41 ;;=> 2.5925925
42
43 ;; now using our new function
44 ((smooth-repeatedly my-impulse-func 1) 2)
45 ;;=> 3.3333333
46 user> ((smooth-repeatedly my-impulse-func 2) 2)
47 ;;=> 3.3333333
48 user> ((smooth-repeatedly my-impulse-func 3) 2)
49 ;;=> 2.5925925
50 )