-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.1.rkt~
91 lines (82 loc) · 2.68 KB
/
1.1.rkt~
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
#lang planet neil/sicp
(display "Exercise 1.1\n")
10
(+ 5 3 4)
(- 9 1)
(/ 6 2)
(+ (* 2 4) (- 4 6))
(define a 3)
(define b (+ a 1))
(+ a b (* a b))
(= a b)
(if (and (> b a) (< b (* a b)))
b
a)
(cond ((= a 4) 6)
((= b 4) (+ 6 7 a))
(else 25))
(+ 2 (if (> b a) b a))
(* (cond ((> a b) a)
((< a b) b)
(else -1))
(+ a 1))
(display "Exercise 1.2\n")
(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5)))))
(* 3 (- 6 2) (- 2 7)))
(display "Exercise 1.3\n")
(define (square a) (* a a))
(define (smallest? a b c)
(if (and (< a b) (< a c)) true false))
(define (exe-1.3 a b c)
(cond ((smallest? a b c) (+ (square b) (square c)))
((smallest? b c a) (+ (square a) (square c)))
(else (+ (square a) (square b)))))
(display "Exercise 1.4\n")
(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))
;the operator for the outer parent is decided based upon the evaluation of the inner one where operator is if
(display "Exercise 1.5\n")
(define (p) (p))
(define (test x y)
(if (= x 0)
0
y))
;In applicative order the function never returns since the interpreter tries to evaluate both operans and since second operand is recursive it never returns anything and blows the callstack.
;In normal order (p) is never evaluated since it is never need sine (= x 0) evaluates to true
(display "Exercise 1.6\n")
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
(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 (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
(define (sqrt x) (sqrt-iter 1 x))
;Because of applicative order the function tries to evaluate both arguments to new-if each time it is called so it ends up in an infinite recursion loop.
(display "Exercise 1.7\n")
(define (good-enough2? guess-old guess-new x)
(< (abs (- 1 (/ guess-old guess-new))) 0.001))
(define (sqrt-iter-helper guess-old guess-new x)
(if (good-enough2? guess-old guess-new x)
guess-new
(sqrt-iter-helper guess-new (improve guess-new x)
x)))
(define (sqrt2 x) (sqrt-iter-helper 0 1 x))
;Meh clobbered together but works and is more precise for smaller numbers
(display "Exercise 1.8\n")
(define (improve-cube guess x)
(/ (+ (/ x (square guess)) (* 2 guess))
3))
(define (cube-root-helper guess-old guess-new x)
(if (good-enough2? guess-old guess-new x)
guess-new
(cube-root-helper guess-new (improve-cube guess-new x)
x)))
(define (cube-root x) (cube-root-helper 0 1 x))