Skip to content

Instantly share code, notes, and snippets.

@schmalz
Created October 9, 2020 13:54
Show Gist options
  • Save schmalz/4a1ac1e85c34af86b1d0556e5e3009fb to your computer and use it in GitHub Desktop.
Save schmalz/4a1ac1e85c34af86b1d0556e5e3009fb to your computer and use it in GitHub Desktop.
LFE SICP square root first example
(defmodule sqrt
(export (sqrt 1)))
(defun sqrt [x]
(sqrt (* 0.5 x)
x))
(defun sqrt [guess x]
(if (good-enough? guess x)
guess
(sqrt (improve guess x)
x)))
(defun good-enough? [guess x]
(< (absv (- (square guess)
x))
0.0001))
(defun improve [guess x]
(average guess
(/ x guess)))
(defun average [x y]
(/ (+ x y)
2))
(defun absv
([x] (when (< x 0))
(- x))
([x]
x))
(defun square [x]
(* x x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment