How can you define a function to reverse a list in Scheme by using foldr
and foldl
?
What we want is a succinct solution to reverse a list in Scheme using a foldl
call and a different solution using a foldr
call, as defined:
(define (foldl operation lst initial)
(if (null? lst) initial
(foldl operation
(cdr lst)
(operation (car lst) initial))))
and
(define (foldr operation lst initial)
(if (null? lst) initial
(operation
(car lst)
(foldr operation (cdr lst) initial))))
The astute person will observe that the foldl
implementation is tail-recursive because the returned value is computed as each recursive step is called - at the last step the entire answer is already computed and simply returned up the chain.
The foldr
implementation is not tail-recursive because it must build the returned value by using the values that are passed back up the recursive chain.
Therefore, the two Scheme implementations that we are interested in should be in the following form,
(define (rev1 lst)
(foldl ___________________________
**Solution:**
(define (rev1 lst)
(foldl cons lst '()))
and
(define (rev2 lst)
(foldr ___________________________
**Solution 1:**
(define (rev2 lst)
(foldr
(lambda (element accumulator)
(foldr cons accumulator (cons element '())))
lst '()))
**Solution 2:**
(define (rev2 lst)
(foldr
(lambda (element accumulator)
(append accumulator (cons element '())))
lst '()))
The end goal is to be able to call the following,
(rev1 '(1 2 3)) -> (3 2 1)
(rev2 '(1 2 3)) -> (3 2 1)
The foldl
solution should be relatively trivial (based on our intuition), but the foldr
solution will probably require some more thought.
Previous questions similar (but far less documented) to this question ended up unanswered and/or closed.