sicp exercise 1.4 and various recursive algorithms
This commit is contained in:
parent
a92e918950
commit
1b3d763cc6
5
exercise1-4.scm
Normal file
5
exercise1-4.scm
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
(define (add-abs a b)
|
||||||
|
((if (> b 0) + -) a b )
|
||||||
|
)
|
||||||
|
|
||||||
|
(print (add-abs 3 -4))
|
5
factorial.scm
Normal file
5
factorial.scm
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
(define (factorial n)
|
||||||
|
(cond ((= n 2) 2)
|
||||||
|
(else (* (factorial (- n 1)) n))))
|
||||||
|
|
||||||
|
(print (factorial 10000))
|
22
newton.scm
Normal file
22
newton.scm
Normal 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 2))
|
37
test-order-of-execution.scm
Normal file
37
test-order-of-execution.scm
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
(define (mainstage-with-if x y)
|
||||||
|
(print "this is mainstage-with-if")
|
||||||
|
(if (< x y) (stage11 x) (stage21 y)))
|
||||||
|
|
||||||
|
(define (mainstage-with-procedure-if x y)
|
||||||
|
(print "this is mainstage-with-if")
|
||||||
|
(procedure-if (< x y) (stage11 x) (stage21 y)))
|
||||||
|
|
||||||
|
(define (stage11 x)
|
||||||
|
(print "this is stage11")
|
||||||
|
(stage12 x))
|
||||||
|
|
||||||
|
(define (stage21 x)
|
||||||
|
(print "this is stage21")
|
||||||
|
(stage22 x))
|
||||||
|
|
||||||
|
(define (stage12 x)
|
||||||
|
(print "this is stage12")
|
||||||
|
(stage13 x))
|
||||||
|
|
||||||
|
(define (stage22 x)
|
||||||
|
(print "this is stage22")
|
||||||
|
(stage23 x))
|
||||||
|
|
||||||
|
(define (stage13 x)
|
||||||
|
(print "this is stage13")
|
||||||
|
x)
|
||||||
|
|
||||||
|
(define (stage23 x)
|
||||||
|
(print "this is stage23")
|
||||||
|
x)
|
||||||
|
|
||||||
|
(define (procedure-if predicate then-clause else-clause)
|
||||||
|
(cond (predicate then-clause) (else else-clause)))
|
||||||
|
|
||||||
|
(print (mainstage-with-if 1 2))
|
||||||
|
(print (mainstage-with-procedure-if 1 2))
|
Loading…
Reference in New Issue
Block a user