2.35
练习 2.35 将2.2.2节的count-leaves重新定义为一个累积:
(define (count-leaves t)
(accumulate <??> <??> (map <??> <??>)))
首先,定义 accumulate
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))
)
)
然后,再定义 enumerate-tree
(define (enumerate-tree tree)
(cond ((null? tree) '())
((not (pair? tree)) (list tree))
(else (append (enumerate-tree (car tree))
(enumerate-tree (cdr tree))))))
(define (count-leaves t)
(accumulate + 0 (map (lambda (x) 1) (enumerate-tree t))))
(define x (cons (list 1 2) (list 3 4)))
(count-leaves x)