diff --git a/ex-5_20-22.scm b/ex-5_20-22.scm new file mode 100644 index 0000000..7df114f --- /dev/null +++ b/ex-5_20-22.scm @@ -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") diff --git a/ex-5_20-xx.scm b/ex-5_23-xx.scm similarity index 66% rename from ex-5_20-xx.scm rename to ex-5_23-xx.scm index cdda6a6..605cde9 100644 --- a/ex-5_20-xx.scm +++ b/ex-5_23-xx.scm @@ -1,4 +1,5 @@ (load "util.scm") (load "misc/sicp-regsim.scm") -(display "\nex-5.20\n") +(display "\nex-5.23\n") +