简体   繁体   中英

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)(cd)(((e)))))) , the output is (((b) (cd) (((e)))) a) .

I want it to be (((((e)))(dc)(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!

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM