Implement till 5.14

main
Felix Martin 2021-03-29 08:28:45 -04:00
parent 284ccb26ad
commit e22a52b7f3
2 changed files with 55 additions and 4 deletions

View File

@ -357,6 +357,14 @@
(display "[ok]\n")
(display "\nex-5.13 - dynamic-registers\n")
;; (load "misc/sicp-regsim.scm")
(display "TBD!\n")
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(begin ;; Allocate register dynamically if needed
(allocate-register name)
(lookup-register name)))))
(display "[ok]\n")

View File

@ -1,6 +1,49 @@
(load "util.scm")
(load "misc/sicp-regsim.scm")
(display "\nex-5.14\n")
(display "\nex-5.14 - factorial-stack-evaluation\n")
(display "\nex-5.15\n")
(define factorial-machine (make-machine
'(n val continue)
(list (list '= =) (list '- -) (list '* *))
'(controller
(assign continue (label fact-done)) ; set up final return address
fact-loop
(test (op =) (reg n) (const 1))
(branch (label base-case))
;; Set up for the recursive call by saving n and continue.
;; Set up continue so that the computation will continue
;; at after-fact when the subroutine returns.
(save continue)
(save n)
(assign n (op -) (reg n) (const 1))
(assign continue (label after-fact))
(goto (label fact-loop))
after-fact
(restore n)
(restore continue)
(assign val (op *) (reg n) (reg val)) ; val now contains n(n - 1)!
(goto (reg continue)) ; return to caller
base-case
(assign val (const 1)) ; base case: 1! = 1
(goto (reg continue)) ; return to caller
fact-done)))
(define (run-machine-for n)
(display "factorial ") (display n)
((factorial-machine 'stack) 'initialize)
(set-register-contents! factorial-machine 'n n)
(start factorial-machine)
; (assert (get-register-contents factorial-machine 'val) 720)
((factorial-machine 'stack) 'print-statistics)
(newline))
(map run-machine-for '(10))
; For each recursion there are two pushes and there are (n - 1) recursions.
; total-pushes(n) = (n - 1) * 2
; max-depth: (n - 1) * 2
(display "\nex-5.15 - instruction-counting\n")
(display "\nex-5.16\n")