2.39 Exercise 2.39
Writing reverse in terms of fold-right uses an inner procedure of
(lambda (x y) (append y (list x))) #<procedure>
y contains the list so far (with an initial value of nil), while x is the current element being folded over. The current element gets added to the end of the list, and since the values in the original list get added in reverse order (due to the way the recursive process unfolds), this produces a reversed list.
(define (reverse sequence) (fold-right (lambda (x y) (append y (list x))) nil sequence))
Writing reverse in terms of fold-left is almost identical, with an inner procedure of
(lambda (x y) (append (list y) x)) #<procedure>
The two arguments of a procedure passed to fold-left are reversed compared to those for fold-right. So now, y is the current element being visited. Since fold-left evolves an iterative process where the elements of the list being reversed are operated on in forward order, appending the values to the front of the list as they are seen produces a list in reversed order.
(define (reverse-foldl sequence) (fold-left (lambda (x y) (append (list y) x)) nil sequence))