Nested function in Clojure with defn and letfn

After reading spoon-bending and delightfull beginning of SICP I tried to write some Clojure.

Resources witch I found usefull enough to check them out before google my question:

Here is what I came up when trying to write the examples in Clojure:

(def square #(* %1 %1))
(def avg #(/ (+ %1 %2) 2))
(def abs? #(if (< %1 0) (- %1) %1))

(defn improve [so-far x]
  (avg so-far
       (/ x so-far)))

(defn good-enough? [so-far x]
  (< (abs? (- (square so-far) x))
     0.00001))

(defn sqrt-newton [so-far x]
  (if (good-enough? so-far x)
      so-far
      (sqrt-newton (improve so-far x)
                   x)))

(def sqrt #(sqrt-newton (/ %1 2) %1))

(defn sqrt [x] (sqrt-newton (/ x 2) x))

and after a while trying to use nested functions:

(def square #(* %1 %1))
(def avg #(/ (+ %1 %2) 2))
(def abs? #(if (< %1 0) (- %1) %1))

(defn sqrt [x]
   (letfn [
    (improve [so-far] (avg so-far (/ x so-far)))
    (good-enough? [so-far] (< (abs? (- x (square so-far)))
                              0.00001))
    (sqrt-newton [so-far] (if (good-enough? so-far)
                              so-far
                              (sqrt-newton (improve so-far))))]
    (sqrt-newton (/ x 2))))

Is it proper way to define local functions. Constructive criticism is very welcome.

Advertisements
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s