This is my Clojure solution to Chapter 1, Exercise 46:
(ns sicp.ch1.ex46
(:require [sicp.ch1.ex06 :as ch1-ex06]
[sicp.ch1.ex35 :as ch1-ex35]))
(defn iterative-improve
[good-enough? improve]
(fn f [guess]
(if (good-enough? guess)
guess
(f (improve guess)))))
(defn sqrt
[x]
((iterative-improve #(ch1-ex06/good-enough? % x)
#(ch1-ex06/improve % x))
1.0))
(defn fixed-point
[f first-guess]
((iterative-improve #(ch1-ex35/close-enough? % (f %))
#(f %))
first-guess))
(comment
(sqrt 16) ; => ~4.0
(sqrt 10000) ; => ~100.0
(fixed-point #(+ 1 (/ 1 %)) 2.0) ; => ~1.618
#__)
No comments:
Post a Comment