Add solutions to exercises from section 1.1

This commit is contained in:
Petar Kapriš 2025-01-15 16:52:59 +01:00
commit 8b37951b28
8 changed files with 88 additions and 0 deletions

28
ex-1.01.txt Normal file
View file

@ -0,0 +1,28 @@
10 -> 10
(+ 5 3 4) -> 12
(- 9 1) -> 8
(/ 6 2) -> 3
(+ (* 2 4) (- 4 6)) -> 6
(define a 3) -> a (3)
(define b (+ a 1)) -> b (4)
(+ a b (* a b)) -> 19
(= a b) -> #f
(if (and (> b a) (< b (* a b)))
b
a)
-> 4
(cond ((= a 4) 6)
((= b 4) (+ 6 7 a))
(else 25))
-> (+ 6 7 a) -> 16
(+ 2 (if (> b a) b a))
-> 6
(* (cond ((> a b) a)
((< a b) b)
(else -1))
(+ a 1))
-> 16

6
ex-1.02.scm Normal file
View file

@ -0,0 +1,6 @@
(/ (+ 5
4
(- 2 (- 3 (+ 6 (/ 4 5)))))
(* 3
(- 6 2)
(- 2 7)))

9
ex-1.03.scm Normal file
View file

@ -0,0 +1,9 @@
#| BEGIN (Write your solution here) |#
(define (sqr x) (* x x))
(define (solution a b c)
(cond ((and (<= a b) (<= a c))
(+ (sqr b) (sqr c)))
((and (<= b a) (<= b c))
(+ (sqr a) (sqr c)))
(else (+ (sqr a) (sqr b)))))
#| END |#

2
ex-1.04.txt Normal file
View file

@ -0,0 +1,2 @@
The if statement will select the appropriate function to execute, if b>0, it
will add b, otherwise it will subtract it.

4
ex-1.05.txt Normal file
View file

@ -0,0 +1,4 @@
If the interpreter uses normal-order evaluation, it will expand test into an
"if", which will then evaluate to 0, if it uses applicative-order evaluation,
it will first evaluate 0 and (p), while trying to evaluate (p), it will enter
an infinite loop.

3
ex-1.06.txt Normal file
View file

@ -0,0 +1,3 @@
The program will run into an infinite loop, because in every execution of
square-iter, the improve function is called again, since this is an
applicative-ordered language

18
ex-1.07.scm Normal file
View file

@ -0,0 +1,18 @@
#| BEGIN (Write your solution here) |#
(define (average a b)
(/ (+ a b) 2))
(define (improve guess x)
(average guess (/ x guess)))
(define (good-enough? guess x)
(< (abs (- (improve guess x) guess)) 0.0001))
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
(define (square-root x)
(sqrt-iter 1.0 x))
#| END |#

18
ex-1.08.scm Normal file
View file

@ -0,0 +1,18 @@
#| BEGIN (Write your solution here) |#
(define (improve guess x)
(/ (+ (/ x guess guess)
(* 2 guess))
3))
(define (good-enough? guess x)
(< (abs (- (improve guess x) guess)) 0.0001))
(define (cbrt-iter guess x)
(if (good-enough? guess x)
guess
(cbrt-iter (improve guess x)
x)))
(define (cube-root x)
(cbrt-iter 1.0 x))
#| END |#