Notes: The exercise 2.37 on Hexlet's site has an error, noted in the comments. Also, their page for exercise 2.38 should probably have 0 tests. And finally, I did not calculate the exact number in the final exercise 2.43, but I included a relevant discussion.
21 lines
544 B
Scheme
21 lines
544 B
Scheme
#lang sicp
|
|
|
|
(define (fold-right op initial sequence)
|
|
(if (null? sequence)
|
|
initial
|
|
(op (car sequence)
|
|
(fold-right op initial (cdr 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))
|
|
|
|
(define (reverse-right sequence)
|
|
(fold-right (lambda (x y) (append y (list x))) nil sequence))
|
|
|
|
(define (reverse-left sequence)
|
|
(fold-left (lambda (x y) (cons y x)) nil sequence))
|