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.
This is a reverse function in Racket which I like much better that Scheme. It uses the match pattern matching function only.
You could simply reverse the elements in a list using foldr:
I used a code similar to insert sort
I am reproducing it from memory. There may be some errors. Will correct the code if thats the case. But the technique used is similar to the commandments for nested lists given in THe Little Schemer :). I checked it in DrRacket
(deep-rev-list '((1 2) (3) ((4 5)))) returns (((5 4)) (3) (2 1))
This uses an accumulator variable to reverse the list, taking the first element off the incoming list and consing it to the front of the accumulator. It hides the accumulator taking function and just exposes the function that takes a list, so the caller doesn't have to pass in the empty list. That's why I have my-reverse-2.
Because the last function call in
my-reverse-2
is a call tomy-reverse-2
, and the return value is passed right through (the return value of the first call is the return value of the second call, and so on)my-reverse-2
is tail optimized, which means it will not run out of room on the stack. So it is safe to call this with a list as long as you like.If you want it to apply to nested lists use something like this:
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.
(deep-reverse '(a (b c d) e))
->'(e (d c b) a)
which is in reverse alphabetical order, despite the fact that there is a nested list. It evaluates as so:My solution:
This is one way that you can make a reverse function that applies to nested lists:
Explanation in pseudo-code:
Start by reversing the list as you would normally do
Then for each element in the reversed list:
- If the element is a list itself: Apply the procedure recursively
- Else: Don't touch the element