Reverse a list in Scheme with foldl and foldr

后端 未结 2 809
小鲜肉
小鲜肉 2021-01-19 19:50

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

2条回答
  •  無奈伤痛
    2021-01-19 20:29

    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)
    

提交回复
热议问题