Say I have the list ‘(1 2 3 (4 5 6) 7 8 9). It should return (9 8 7 (6 5 4) 3 2 1) using the following code below. I’m trying to understand how this iterative process works. Showing how this is done step by step would be very helpful.
The part I get confused the most is when deep-reverse is called twice at this point
(append
(deep-reverse (cdr lst))
(list (deep-reverse (car lst)))))
I don’t know what happens then.
(define (deep-reverse lst)
(cond ((null? lst) '() )
((pair? (car lst))
(append
(deep-reverse (cdr lst))
(list (deep-reverse (car lst)))))
(else
(append
(deep-reverse (cdr lst))
(list (car lst))))))
Well, I just answered something like this here, but I didn’t really go into detail on the deep-reverse.
What happens is it reverses each item that happens to be a list before appending it to the end of the list. Imagine what would happen if it didn’t call deep-reverse on the car of the list:
(reverse '(a (b c d) e)isWith deep-reverse it would look something like
Which is
Here is another version of deep-reverse, written differently, if that makes it clearer.
This version of deep-copy uses an accumulator and is tail recursive.
This checks to see if the element is a list before adding it to the list, and if it is, reverses it first. Since it calls itself to revers the inner list, it can handle arbitrary nesting.
which is in reverse alphabetical order, despite the fact that there is a nested list. It evaluates as so: