How to Reverse a List?

2019-01-11 15:16发布

What is the function to a list in Scheme? It needs to be able to handle nested lists.

So that if you do something like (reverse '(a (b c d) e)) you'll get (e (b c d) a) as the output.

How should I approach this problem? I'm not just looking for an answer, but something that will help me learn.

7条回答
姐就是有狂的资本
2楼-- · 2019-01-11 16:02
(define (reverse1 l)
  (if (null? l)
     nil
     (append (reverse1 (cdr l)) (list (car l)))
  )
)

Explanation:

Rules:
1. If list is empty, then reverse list is also empty
2. else behind reverse tail of the list add first element of the list

Look at at this code this way:

reverse1 is name of the function, l is parameter
if list is empty then reverse is also empty else call reverse1 function with (cdr l) which is tail of list and append that to first alement (car l) that you make as a list

in your example (pseudo cod):

1st iteration 
l=>(a (bcd)e)
car l => a
cdr l => (bcd)e
list(car l) =>(a)
------------------
reverse( cdr l)"+"(a)
------------------
2nd iteration
l=>((bcd)e)
car l => (bcd)
cdr l =>e
list(car l)=>(bcd)
--------------------
reverse(cdr l)"+"((bcd))+(a)
-----------------------
3rd iteration
l=>e
car l=> e
cdr l => nil
list (car l) =>(e)
-------------------------
(e (bcd)a)
查看更多
登录 后发表回答