Implement till 5.6
This commit is contained in:
parent
73f59656c8
commit
82128a6445
@ -161,4 +161,78 @@
|
||||
(expt-iter 3 4))
|
||||
|
||||
(display "\nex-5.5 - hand-simulate-fib\n")
|
||||
(display "[answered]\n")
|
||||
|
||||
; begin
|
||||
; n = 2 ; val = ? ; continue = fib-done
|
||||
; stack = []
|
||||
|
||||
; fib-loop
|
||||
; n = 1 ; val = ? ; continue = afterfib-n-1
|
||||
; stack = [2, fib-done]
|
||||
|
||||
; fib-loop
|
||||
; immediate-answer
|
||||
; n = 1 ; val = 1 ; continue = afterfib-n-1
|
||||
; stack = [2, fib-done]
|
||||
|
||||
; afterfib-n-1
|
||||
; n = 0 ; val = 1 ; continue = afterfib-n-2
|
||||
; stack = [1, fib-done]
|
||||
|
||||
; fib-loop
|
||||
; n = 0 ; val = 0 ; continue = afterfib-n-2
|
||||
; stack = [1, fib-done]
|
||||
|
||||
; afterfib-n-2
|
||||
; n = 0 ; val = 1 ; continue = fib-done
|
||||
; stack = []
|
||||
|
||||
; fib-done
|
||||
; val = 1
|
||||
|
||||
(display "\nex-5.6 - slightly-improved-fib\n")
|
||||
|
||||
(define fib-machine
|
||||
(make-machine
|
||||
'(n val continue)
|
||||
(list (list '< <) (list '- -) (list '= +) (list '+ +))
|
||||
'(controller
|
||||
(assign continue (label fib-done))
|
||||
fib-loop
|
||||
(test (op <) (reg n) (const 2))
|
||||
(branch (label immediate-answer))
|
||||
;; set up to compute Fib(n - 1)
|
||||
(save continue)
|
||||
(assign continue (label afterfib-n-1))
|
||||
(save n) ; save old value of n
|
||||
(assign n (op -) (reg n) (const 1)); clobber n to n - 1
|
||||
(goto (label fib-loop)) ; perform recursive call
|
||||
afterfib-n-1 ; upon return, val contains Fib(n - 1)
|
||||
(restore n)
|
||||
;(restore continue)
|
||||
;; set up to compute Fib(n - 2)
|
||||
(assign n (op -) (reg n) (const 2))
|
||||
;(save continue)
|
||||
(assign continue (label afterfib-n-2))
|
||||
(save val) ; save Fib(n - 1)
|
||||
(goto (label fib-loop))
|
||||
afterfib-n-2 ; upon return, val contains Fib(n - 2)
|
||||
(assign n (reg val)) ; n now contains Fib(n - 2)
|
||||
(restore val) ; val now contains Fib(n - 1)
|
||||
(assign val ; Fib(n - 1) + Fib(n - 2)
|
||||
(op +) (reg val) (reg n))
|
||||
(restore continue)
|
||||
(goto (reg continue)) ; return to caller, answer is in val
|
||||
immediate-answer
|
||||
(assign val (reg n)) ; base case: Fib(n) = n
|
||||
(goto (reg continue))
|
||||
fib-done)))
|
||||
|
||||
(set-register-contents! fib-machine 'n 8)
|
||||
(start fib-machine)
|
||||
(assert (get-register-contents fib-machine 'val) 21)
|
||||
|
||||
; restore and save of continue in afterfib-n-1 is not needed
|
||||
(display "[answered]\n")
|
||||
|
8
ex-5_07-xx.scm
Normal file
8
ex-5_07-xx.scm
Normal file
@ -0,0 +1,8 @@
|
||||
(load "util.scm")
|
||||
(load "misc/sicp-regsim.scm")
|
||||
|
||||
|
||||
(display "\nex-5.7\n")
|
||||
|
||||
|
||||
(display "\nex-5.8\n")
|
Loading…
Reference in New Issue
Block a user