Skip to content

Instantly share code, notes, and snippets.

@kingcons
Last active August 8, 2018 20:30
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 kingcons/8071c6a214bc82d09be398250d9b3953 to your computer and use it in GitHub Desktop.
Save kingcons/8071c6a214bc82d09be398250d9b3953 to your computer and use it in GitHub Desktop.
A cute program to compute nth-roots, extracted from SICP exercises
(defun average-damp (fn)
(lambda (x)
(/ (+ x (funcall fn x)) 2)))
(defun compose (f g)
(lambda (x)
(funcall f (funcall g x))))
(defun repeated (fn n)
(labels ((iter (i &optional result)
(if (= i n)
result
(iter (1+ i) (compose fn result)))))
(iter 1 fn)))
(defun fixed-point (fn initial-guess &key (log nil) (tolerance 0.0001))
(labels ((close-enough-p (x y)
(< (abs (- x y)) tolerance))
(try (guess)
(let ((next (funcall fn guess)))
(when log
(format t "Guess: ~A~%" guess))
(if (close-enough-p guess next)
next
(try next)))))
(try initial-guess)))
(defun fixed-point-transform (fn transform guess)
(fixed-point (funcall transform fn) guess))
(defun nth-root (n x)
(flet ((find-root (y) (/ x (expt y (1- n)))))
(let ((nth-damp (repeated #'average-damp (log n 2))))
(fixed-point-transform #'find-root nth-damp 1.0))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment