Question

I have some code that is supposed to take a list and return the reverse of that list. However, it just returns the list. Here is the code

(define (reverse listx)
  (define (thing list1 list2)
    (if (null? list1)
        list2
        (thing (cdr list1) (append list2 (list (car list1))))
        )
    )
  (thing listx nil)
  )

The problem I think hinges on the fact that

 (append nil 1) => 1

rather than

 (append nil 1) => (1)
Was it helpful?

Solution

No, that's not it: you do call (append list2 (list ...)), with the 2nd arg enclosed in a list.

The problem is that you use append while you ought to use simple cons there: (thing (cdr list1) (cons (car list1) list2)).

With cons, each new element from list1 will go on top (i.e. "to the left of") the previously handled ones, hence building the result in reverse:

(a b c d e)
--------------------------
(a b c d e)             ()
  (b c d e)            (a)
    (c d e)          (b a)
      (d e)        (c b a)
        (e)      (d c b a)
         ()    (e d c b a)
--------------------------
               (e d c b a)

But with append you're just recreating the same list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top