SICP/ex-5_01-xx.scm

51 lines
1.2 KiB
Scheme
Raw Normal View History

2021-03-17 01:25:41 +01:00
(load "util.scm")
(load "misc/sicp-regsim.scm")
2021-03-17 01:25:41 +01:00
(display "\nex-5.1 draw-factorial\n")
; See misc directory for drawing.
(display "[answered]\n")
(display "\nex-5.2 design-factorial\n")
(define factorial-machine
(make-machine
'(counter product n)
(list (list '> >) (list '* *) (list '+ +))
'(controller
(assign product (const 1))
(assign counter (const 1))
test-counter
(test (op >) (reg counter) (reg n))
(branch (label factorial-done))
(assign product (op *) (reg product) (reg counter))
(assign counter (op +) (reg counter) (const 1))
(goto (label test-counter))
factorial-done)))
(set-register-contents! factorial-machine 'n 6)
(start factorial-machine)
(assert (get-register-contents factorial-machine 'product) 720)
(display "\nex-5.3 - sqrt-newton\n")
(define (sqrt-newton n)
(define (improve guess)
(average guess (/ n guess)))
(define (average a b)
(/ (+ a b) 2))
(define (good-enough? guess)
(< (abs (- (* guess guess) n)) 0.01))
(define (iter guess)
(if (good-enough? guess)
guess
(iter (average guess (/ n guess)))))
(iter 1.))
(display (sqrt-newton 2))
;(display "\nex-5.4\n")