Created
November 12, 2012 02:58
-
-
Save monmon/4057253 to your computer and use it in GitHub Desktop.
SICP q2.35
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (define nil '()) | |
| (define (accumulate op initial sequence) | |
| (if (null? sequence) | |
| initial | |
| (op (car sequence) | |
| (accumulate op initial (cdr sequence))))) | |
| ; 2.2.2 | |
| (define (count-leaves x) | |
| (cond ((null? x) 0) | |
| ((not (pair? x)) 1) | |
| (else (+ (count-leaves (car x)) | |
| (count-leaves (cdr x)))))) | |
| (define x (cons (list 1 2) (list 3 4))) | |
| (print (count-leaves x)) | |
| (print (count-leaves (list x x))) | |
| ;---------------------------------------------------------------------------- | |
| ; p.67で木の葉を数え上げる enumerate-tree を作った | |
| ; また、p.65で「cont-leaves 手続きに類似のsum-odd-squares」というヒントがあるので | |
| ; sum-odd-squaresとにたものになるはず | |
| (define (enumerate-tree tree) | |
| (cond ((null? tree) nil) | |
| ((not (pair? tree)) (list tree)) | |
| (else (append (enumerate-tree (car tree)) | |
| (enumerate-tree (cdr tree)))))) | |
| ; つまり、 | |
| ; enumerate-tree で木の葉一覧を作り、 | |
| ; それをmapで全て1にし、 | |
| ; それらを全て足せば木の葉の数が出る | |
| (define (count-leaves t) | |
| (accumulate + 0 (map (lambda (x) 1) (enumerate-tree t)))) | |
| (print (count-leaves x)) | |
| (print (count-leaves (list x x))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment