SICP/ex-5_20-22.scm

49 lines
1.2 KiB
Scheme
Raw Normal View History

2021-04-02 01:51:12 +02:00
(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")