more exercises done

This commit is contained in:
Marco 2024-09-26 21:29:47 +02:00
parent 9a7a74f952
commit cfabf8a122
6 changed files with 110 additions and 0 deletions

View File

@ -0,0 +1,10 @@
(define (A x y)
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(else (A (- x 1) (A x (- y 1))))))
(print (A 0 10))
(print (A 1 10))
(print (A 2 4))
(print (A 15 1))

View File

@ -0,0 +1,17 @@
(define (fn-recursive n)
(cond ((< n 3) n)
(else (+ (fn-recursive (- n 1)) (* 2 (fn-recursive (- n 2))) (* 3 (fn-recursive (- n 3)))))))
(define (fn-wrapper n)
(define (fn-iterative n1 n2 n3 count)
(cond ((= count 0) n1)
(else (fn-iterative (+ n1 (* 2 n2) (* 3 n3)) n1 n2 (- count 1) ))))
(if (< n 3)
n
(fn-iterative 2 1 0 (- n 2)))
)
(print (fn-recursive 10))
(print (fn-wrapper 10))

View File

@ -0,0 +1,11 @@
(define (pascal-x-y column row)
(cond ((= column 0) 1)
((= column row) 1)
((= row 0) 1)
((> column row) 0)
(else (+ (pascal-x-y (- column 1) (- row 1)) (pascal-x-y column (- row 1)))))
)
(print (pascal-x-y 0 0))
(print (pascal-x-y 0 4))
(print (pascal-x-y 3 4))

View File

@ -0,0 +1,28 @@
;this program does not work, it will cause an infinite loop
(define (sqrt_iter new_guess last_guess x)
(new-if (good_enough? new_guess last_guess)
new_guess
(sqrt_iter (improve new_guess x) new_guess x)
)
)
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
(define (improve guess x)
(/ (+ guess (/ x guess)) 2))
(define (good_enough? guess last_guess)
(< (absolute (- guess last_guess)) 0.000000000000001))
(define (absolute x)
(if (< x 0)
(- 0 x)
x))
(define (sqrt x) (sqrt_iter (/ x 2.0) x x))
(print (sqrt 10))

View File

@ -0,0 +1,22 @@
(define (sqrt_iter new_guess last_guess x)
(if (good_enough? new_guess last_guess)
new_guess
(sqrt_iter (improve new_guess x) new_guess x)
)
)
(define (improve guess x)
(/ (+ guess (/ x guess)) 2))
(define (good_enough? guess last_guess)
(< (absolute (- guess last_guess)) 0.000000000000001))
(define (absolute x)
(if (< x 0)
(- 0 x)
x))
(define (sqrt x) (sqrt_iter (/ x 2.0) x x))
(print (sqrt 10))

View File

@ -0,0 +1,22 @@
(define (cuberoot_iter new_guess last_guess x)
(if (good_enough? new_guess last_guess)
new_guess
(cuberoot_iter (improve new_guess x) new_guess x)
)
)
(define (improve guess x)
(/ (+ (/ x (* guess guess)) (* 2 guess)) 3))
(define (good_enough? guess last_guess)
(< (absolute (- guess last_guess)) 0.000000000000001))
(define (absolute x)
(if (< x 0)
(- 0 x)
x))
(define (cbrt x) (cuberoot_iter (/ x 2.0) x x))
(print (cbrt 27))