The problem with your code is that you're passing the parameters in the wrong order - when using cons
to build a list, the first parameter is the new element we want to stick at the beginning of the list, and the second one is the list we've built so far.
Having said that, reversing a list using foldl
is a bit simpler and you don't need to use append
at all - in fact, it's a bad practice using append
when cons
suffices:
(define (rvsl sequence)
(foldl cons
'()
sequence))
Why this works? let's rewrite the function being more explicit this time:
(define (rvsl sequence)
(foldl (lambda (current accumulated)
(cons current accumulated))
'()
sequence))
Now we can see that the lambda
procedure receives two parameters: the current
element in the input list, and the accumulated
value so far - good parameter names make all the difference in the world! this is much, much clearer than calling the parameters x
and y
, which says nothing about them.
In this case, we just want to cons
the current element at the head of the accumulated value (which starts as an empty list), hence producing a reversed list as the output. Given that the lambda
procedure receives two parameters and passes them in the same order to cons
, we can simplify the whole thing and just pass the cons
procedure as a parameter.