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 i
This looks like homework, so I'll give you some hints to get you started. The foldl
case is trivial, you just have to discover the right function to pass, and remember: foldl
can be visualised as processing the list backwards (last element first, first element last), so all you have to do is stick together the current element in the list with the accumulated value:
(define (rev1 lst)
(foldl <???> lst '()))
The foldr
case is only slightly harder, just remember that foldr
processes the elements in the list in the same order as they appear in the input list. Again, you have to discover the correct procedures to call:
(define (rev2 lst)
(foldr (lambda (e a)
<???>)
lst
'()))
You need to somehow put e
(the current element) at the end of a
, the accumulated value. Hint: you'll find that append
and list
are useful here.
Your rev1
'solution' doesn't compile... it would if you replaced list
with l
> (define (rev1 l)
(foldl cons l '()))
> (rev1 '(1 2 3))
(3 2 1)
For your rev2
this works as the body:
> (foldr (lambda (a b) (append b (list a))) '(1 2 3) '())
(3 2 1)