Created
October 30, 2019 15:22
-
-
Save chelseatroy/ef547b733e95f4cca985d011fc7303e1 to your computer and use it in GitHub Desktop.
Fold Left and Fold Right
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
| ; 2.38 | |
| (define (fold-right op initial sequence) | |
| (accumulate op initial sequence)) | |
| (define (fold-left op initial sequence) | |
| (define (iter result rest) | |
| (if (null? rest) | |
| result | |
| (iter (op result (car rest)) | |
| (cdr rest)))) | |
| (iter initial sequence)) | |
| (fold-right / 1 (list 1 2 3)) ;--------> 1 1/2 | |
| (fold-left / 1 (list 1 2 3)) ;--------> 1/6 | |
| (fold-right list null (list 1 2 3)) ;--> '(1 (2 (3 ()))) | |
| (fold-left list null (list 1 2 3)) ;--> '(((() 1) 2) 3) | |
| ; 2.39 | |
| (define (reverse sequence) | |
| (fold-right (lambda x y) (append y (list x)) null sequence)) | |
| (define (reverse sequence) | |
| (fold-left (lambda x y) (cons (y x)) null sequence)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment