Answer 5.20

main
Felix Martin 2021-04-01 19:51:12 -04:00
parent ea9b0dd752
commit 927f9e6f21
2 changed files with 50 additions and 1 deletions

48
ex-5_20-22.scm Normal file
View File

@ -0,0 +1,48 @@
(load "util.scm")
(load "misc/sicp-regsim.scm")
(display "\nex-5.20 - box-and-pointer\n")
(define x (cons 1 2))
(define y (list x x))
; | Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
; |-------|---|---|---|---|---|---|---|
; |the-car| | n1| p1| p1| | | |
; |the-cdr| | n2| p3| e0| | | |
(display "[done]\n")
(display "\nex-5.21 - count-leaves\n")
(define (count-leaves tree)
(cond ((null? tree) 0)
((not (pair? tree)) 1)
(else (+ (count-leaves (car tree))
(count-leaves (cdr tree))))))
(define (not-pair? x) (not (pair? x)))
(define count-leaves-machine
(make-machine
'(tree val continue)
(list (list 'cons cons) (list 'car car) (list 'cdr cdr)
(list 'not-pair? not-pair?) (list 'null? null?))
'(controller
(assign val (const 0))
(assign continue (label count-done))
count-leaves
(test (op null?) (reg tree))
(branch (label null-case))
(test (op not-pair?))
(branch (label not-pair-case))
null-case
not-pair-case
(goto (reg continue))
count-done)))
(set-register-contents! count-leaves-machine 'tree '())
(start count-leaves-machine)
(assert (get-register-contents count-leaves-machine 'val) 0)
(display "\nex-5.22\n")

View File

@ -1,4 +1,5 @@
(load "util.scm")
(load "misc/sicp-regsim.scm")
(display "\nex-5.20\n")
(display "\nex-5.23\n")