SICP 习题2.35 count-leaves 用accumulate实现

来源:互联网 发布:原知宏大野智 编辑:程序博客网 时间:2024/05/21 14:54

这题开始我想着用emumerate-tree来做,但是这样做根本就不需要accumulate,后来上网看了别人的做法,我对于递归的理解实在是太浅显。

(define (accumulate op initial sequence)  (if (null? sequence)    initial    (op (car sequence)        (accumulate op initial (cdr sequence)))))(define (count-leaves t)  (accumulate +              0               (map (lambda (sub-t)                     (if (pair? sub-t)                        (count-leaves sub-t) 1))                   t)))(newline)(display (count-leaves (list 1 (list 2 (list 3 4)) 5)))(newline)(display (count-leaves (list (list 1 2) (list 3 (list 4 5) 6))))
0 0
原创粉丝点击