-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbawp.scm
104 lines (78 loc) · 1.94 KB
/
bawp.scm
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
;; Square something
(define (square x) (* x x))
;; Sum of squares
(define (sum-of-squares x y ) (+ (square x) (square y)))
;; Absolute value using cond
(define (abs x)
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (- x))))
;; Another way to eval absolute value
(define (abs2 x)
(cond ((< x 0) (- x))
(else x)))
;; Absolute value with if expression
(define (abs3 x)
(if (< x 0)
(- x)
x))
;; A cond that can be undefined
;; With values 1, or less than 0
(define (uncond x)
(cond ((> x 1) x)
((= x 0) 0)))
;; Example of or/not
(define (>= x y)
(or (> x y) (= x y)))
;; alternatively: (not (< x y))
;; START Exercise 1.1 ;;
10 ; a
(+ 5 3 4) ; b
(- 9 1) ; c
(/ 6 2) ; d
(+ (* 2 4) (- 4 6)) ; e
(define a 3) ; f
(define b (+ a 1)) ; g
(+ a b (* a b)) ; h
(= a b) ; i
(if (and (> b a) (< b (* a b))) ; j
b
a)
(cond ((= a 4) 6)
((= b 4) (+ 6 7 a))
(else 25)) ; k
(+ 2 (if (> b a) b a)); l
(* (cond ((> a b) a)
((< a b) b)
(else -1))
(+ a 1))
;; END Exercise 1.1 ;;
;; START Exercise 1.2 ;;
(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5)))))
(* 3 (- 6 2) (- 2 7)))
;; END Exercise 1.2 ;;
;; START Exercise 1.3 ;;
(define (sum-largest-2 x y z)
(sum-of-squares (or (and (> x y) x) y)
(or (and (> z x) z) x)))
;; END Exercise 1.3 ;;
;; Square root by Newton's method
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
;; A guess is improved by avging it with the quotient of the radicand
;; and the old gues
(define (improve guess x)
(average guess (/ x guess)))
;; Where
(define (average x y)
(/ (+ x y) 2))
;; By good-enough? we mean we are close enough:
;; the square differs from the radicand by less than predetermined tolerence
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
;; Finally we can always guess that the sqrt is 1
(define (sqrt x)
(sqrt-iter 1.0 x))