灯下 登录
计算机科学 / SICP / 5.3.1 Memory as Vectors

Exercise 5.21 · 习题

Exercise 5.21: Implement register machines for
the following procedures. Assume that the list-structure memory operations are
available as machine primitives.

Recursive count-leaves:

(define (count-leaves tree)
(cond ((null? tree) 0)
((not (pair? tree)) 1)
(else
(+ (count-leaves (car tree))
(count-leaves (cdr tree))))))

Recursive count-leaves with explicit counter:

(define (count-leaves tree)

(define (count-iter tree n)

(cond ((null? tree) n)

((not (pair? tree)) (+ n 1))

(else

(count-iter

(cdr tree)

(count-iter (car tree)

n)))))

(count-iter tree 0))

练习 5.21:为以下过程实现寄存器机器。假设表结构内存操作作为机器基本操作已经可用。

递归型 count-leaves:

(define (count-leaves tree)
(cond ((null? tree) 0)
((not (pair? tree)) 1)
(else
(+ (count-leaves (car tree))
(count-leaves (cdr tree))))))

带显式计数器的递归型 count-leaves:

(define (count-leaves tree)
(define (count-iter tree n)
(cond ((null? tree) n)
((not (pair? tree)) (+ n 1))
(else
(count-iter
(cdr tree)
(count-iter (car tree)
n)))))
(count-iter tree 0))