Created
November 12, 2012 03:00
-
-
Save monmon/4057259 to your computer and use it in GitHub Desktop.
SICP q2.38
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 fold-right accumulate) | |
| (define (fold-left op initial sequence) | |
| (define (iter result rest) | |
| (if (null? rest) | |
| result | |
| (iter (op result (car rest)) | |
| (cdr rest)))) | |
| (iter initial sequence)) | |
| (print (fold-right / 1 (list 1 2 3))) ; 3/2 = 1/(2/(3/1)) | |
| (print (fold-left / 1 (list 1 2 3))) ; 1/6 = ((1/1)/2)/3 | |
| (print (fold-right list nil (list 1 2 3))) ; (1 (2 (3 ()))) | |
| (print (fold-left list nil (list 1 2 3))) ; (((() 1) 2) 3) | |
| ; 交換法則が成り立てば同じ値になる |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
initialが単位元なら結合だけでいいよね