Answer 5.20
parent
ea9b0dd752
commit
927f9e6f21
|
@ -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")
|
|
@ -1,4 +1,5 @@
|
|||
(load "util.scm")
|
||||
(load "misc/sicp-regsim.scm")
|
||||
|
||||
(display "\nex-5.20\n")
|
||||
(display "\nex-5.23\n")
|
||||
|
Loading…
Reference in New Issue