Skip to content

Instantly share code, notes, and snippets.

@iArnold
Created June 30, 2017 09:51
Show Gist options
  • Save iArnold/2ef23f8d16c002c96934a1c8015e4ec6 to your computer and use it in GitHub Desktop.
Save iArnold/2ef23f8d16c002c96934a1c8015e4ec6 to your computer and use it in GitHub Desktop.
Squareroot in Lisp en Red
; https://repl.it/languages/scheme
(define (abs x)
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (- x))))
(define (average x y)
(/ (+ x y) 2))
(define (square x) (* x x))
(define (improve guess x)
(average guess (/ x guess)))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
(define (sqrt x)
(sqrt-iter 1.0 x))
(sqrt 3)
; met new-if eindeloze lus.
; nu in Red
abs: function [
x
][
case [
(x > 0) [return x]
(x = 0) [return 0]
(x < 0) [return negate x]
]
]
average: function [
x y
][
(x + y) / 2
]
square: function [
x
][
x * x
]
improve: function [
guess x
][
average guess (x / guess)
]
good-enough?: function [
guess x
][
(abs ((square guess) - x)) < 0.001
]
sqrt-iter: function [
guess x
][
print guess
either good-enough? guess x [
guess
][
sqrt-iter (improve guess x) x
]
]
sqrt2: function [
x
][
sqrt-iter 1.0 x
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment