o.o
o.o

Reputation: 3751

Scheme reverse a list

I am trying to reverse a list in Scheme using DrRacket.

Code:

(define rev
  (lambda(l)
    (if (null? l)
        '()
        (append (rev (cdr l)) (list (car l))))))

If I input (rev '(a((b)(c d)(((e)))))), the output is (((b) (c d) (((e)))) a).

I want it to be (((((e)))(d c)(b))a). I looked here: How to Reverse a List? but I get an even worse output. What am I doing wrong? Any help would be appreciated!

Upvotes: 2

Views: 845

Answers (2)

teshnizi
teshnizi

Reputation: 71

This code will do it:

(define (rev-list lst)
  (if (null? lst)
      null
      (if (list? lst)
          (append (rev-list (cdr lst)
                  (list (rev-list (car lst))))
          lst)))

And the result is:

>>> (display (rev-list '((1 7) 5 (2 4 (5 9))) ))
(((9 5) 4 2) 5 (7 1))

The idea is simple: Return the arg if it's not a list, return rev-list(arg) otherwise.

Upvotes: 1

Óscar López
Óscar López

Reputation: 236034

This is trickier than it looks, you're trying to do a "deep reverse" on a list of lists, not only the elements are reversed, but also the structure … here, try this:

(define (rev l)
  (let loop ((lst l)
             (acc '()))
    (cond ((null? lst) acc)
          ((not (pair? lst)) lst)
          (else (loop (cdr lst) 
                      (cons (rev (car lst))
                            acc))))))

It works as expected:

(rev '(a ((b) (c d) (((e))))))
=> '(((((e))) (d c) (b)) a)

Upvotes: 2

Related Questions