summaryrefslogtreecommitdiffstats
path: root/one/six.scm
blob: e60d1ee33501d1616c5a945b5d624e5a5663650a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
;;; Under Creative Commons Attribution-ShareAlike 4.0
;;; International. See
;;; <https://creativecommons.org/licenses/by-sa/4.0/>.

(define-module (one six)
   #:export (sqrt-sicp sqrt-nif square good-enough? new-if improve))

(define (square x)
  (* x x))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(define (average x y)
  (/ (+ x y) 2))

(define (improve guess x)
  (average guess (/ x guess)))

(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-iter-nif guess x)
  (new-if (good-enough? guess x)
          guess
          (sqrt-iter-nif (improve guess x)
                         x)))

(define (sqrt-sicp x)
  (sqrt-iter 1.0 x))

(define (sqrt-nif x)
  (sqrt-iter-nif 1.0 x))