kvway
kvway

Reputation: 494

List reverse recursively

Here's a code which reverse a list recursively in lisp :

( defun rev1( list final )
    ( if ( eq list () )
    final
        ( rev1( cdr list )  ( cons ( car list ) final ) ) ) )

( defun rev( list )
   ( rev list nil ) )

Could anyone explain me how the assignment between cons cell and the variable final works? Is it pointer to the head ( car ) of that cons cell?

Upvotes: 0

Views: 64

Answers (1)

user1461328
user1461328

Reputation: 742

The final is nil at the beginning and you just cons the first element of a list onto it each time. e.g. you have a list say '( a b c) and the first run will make the final to be '(a) and the recursive call will be (rev1 '(b c) '(a)) accordingly.

And then it goes like this: (rev1 '(c) '(b a))

this goes on and when the list is nil, the final variable is '(c b a), which is you want.

Upvotes: 1

Related Questions