Reverse a list in Scheme with foldl and foldr

痴心易碎 提交于 2019-12-01 18:49:30

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!