Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

list - LISP: multi-level recursive reverse function

How to reverse a list such that every sublist is also reversed? This is what I have so far:

(defun REV (L)
  (cond
    ((null L) nil)
    ((listp L)
     (append
      (REV (cdr L))
      (list (car L))))
    (t
     (append
      (REV (cdr L)) 
      (list (car L))))))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are on the right track, but your last two conditions have the same action, which should give an indication that one of them is not doing what it should. Indeed, the second condition, the listp case, is not right, because when it's a list, you need to append the reverse of that list instead of the unmodified list. A possible solution:

(defun my-reverse (l)
  (cond ((null l) nil)
        ((listp (car l)) (append (my-reverse (cdr l)) 
                                 (list (my-reverse (car l)))))
        (t
          (append (my-reverse (cdr l)) 
                  (list (car l))))))

>  (my-reverse '((1 2 3) (4 5 6)))
((6 5 4) (3 2 1))

As you can see, the only difference is that you test if the first element is a list, and if it is, you reverse the first element before appending it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...