Created
November 12, 2012 02:59
-
-
Save monmon/4057254 to your computer and use it in GitHub Desktop.
SICP q2.36
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))))) | |
| (define (accumulate-n op init seqs) | |
| (if (null? (car seqs)) | |
| nil | |
| (cons (accumulate op init (map (lambda (x) (car x)) seqs)) | |
| (accumulate-n op init (map (lambda (x) (cdr x)) seqs))))) | |
| ; (define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12))) | |
| ; というsがあり、 | |
| ; (accumulate-n + 0 s) | |
| ; を実行すると | |
| ; (list 22 26 30) | |
| ; になる | |
| ; | |
| ; (list 22 26 30) を置き換える | |
| ; | |
| ; (cons 22 (cons 26 (cons 30 nil))) | |
| ; (cons (+ 1 4 7 10) (cons 26 (cons 30 nil))) | |
| ; (cons (accumulate + 0 (list 1 4 7 10)) (cons 26 (cons 30 nil))) | |
| ; | |
| ; つまり、 | |
| ; (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)) | |
| ; から | |
| ; (list 1 4 7 10) | |
| ; をどう作るかを考える | |
| ; | |
| ; 要素の数は同じなのでmapが使えそう | |
| ; それぞれ先頭を取り出しているだけなのでcarで取り出せば良い | |
| ; (list 1 4 7 10) | |
| ; 残り(cdr)で新しいlistを作れば同じことの繰り返しになる | |
| ; (list (list 2 3) (list 5 6) (list 8 9) (list 11 12)) | |
| (define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12))) | |
| (print (accumulate-n + 0 s)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(define (accumulate-n op init seqs)
(if (null? (car seqs))
nil
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))
; で大丈夫!