Exercise 2.39: Complete the following definitions of reverse (exercise 2.18) in terms of fold-right
and
fold-left
from exercise 2.38:
(define (reverse sequence)
(fold-right (lambda (x y) <??>) nil sequence))
(define (reverse sequence)
(fold-left (lambda (x y) <??>) nil sequence))
(define (fold-right fn init-value items)
(if (null? items)
init-value
(fn (car items)
(fold-right fn init-value (cdr items)))))
(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))) '() sequence))
(define (reverse-left sequence)
(fold-left (lambda (x y) (cons y x)) '() sequence))
> (reverse-right (list 1 2 3))
(3 2 1)
> (reverse-left (list 1 2 3))
(3 2 1)