Skip to content

Instantly share code, notes, and snippets.

@DavidYKay
Created March 22, 2016 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidYKay/0eb773ae353a2c5ae5e5 to your computer and use it in GitHub Desktop.
Save DavidYKay/0eb773ae353a2c5ae5e5 to your computer and use it in GitHub Desktop.
Implementation of the square root function, based on SICP Lecture 1A
(ns example.square-root)
(def tolerance 0.00000000001)
(defn square [x]
(* x x))
(defn avg [& args]
(/ (apply + args)
(count args)))
(defn abs [x]
(if (>= x 0)
x
(- x)))
(defn improve-guess [g x]
(avg g (/ x g)))
(defn close-enough? [g x]
(< (abs (- x (square g)))
tolerance))
(defn attempt [g x]
(if (close-enough? g x)
g
(attempt (improve-guess g x) x)))
(defn square-root [x]
(attempt 1 x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment