Created
October 9, 2020 13:54
-
-
Save schmalz/4a1ac1e85c34af86b1d0556e5e3009fb to your computer and use it in GitHub Desktop.
LFE SICP square root first example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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