Sunday, December 27, 2015

I am Coding with a Lisp...

Decided to know more about functional programming so started to play with Clojure using Programming Clojure as my guide... I know that Clojure has its roots in Lisp, so that reminded of SICP... I've heard that this book is really dense, but thought that this might be right moment to have a stab at reading it. Bought it. :) I watched the MIT OCW Lectures that inspired the book though, thus I reckoned that would be fun to implement the first program showed in the course using Clojure.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
(ns square-root.core
  (:gen-class))

(defn square-root [x precision]
  (defn guess-close-enough? [guess x]
    (< (Math/abs (- (Math/pow guess 2) x)) precision))
  (defn improve-guess [guess x] (/ (+ guess (/ x guess)) 2))
  (defn try-guess [guess]
    (if (guess-close-enough? guess x) guess (try-guess (improve-guess guess x))))
  (try-guess 1)
  )

(defn -main
  "Computes the square root"
  [& args]
  (def x 2.0)
  (def precision 0.001)
  (println (format "SQUARE ROOT OF %.3f: %.3f" x (float (square-root x precision))))
  )

My knowledge of Clojure and Leiningen is rather primitive at the moment, but I was able to setup IntelliJ to have a more or less decent development environment (using Cursive). I need to figure out how to implement unit tests though... TDD is a must.