了解深度逆向
假设我有一个列表 '(1 2 3 (4 5 6) 7 8 9)。使用以下代码应返回 (9 8 7 (6 5 4) 3 2 1)。我试图理解这个迭代过程是如何运作的。展示这是如何一步一步完成的将会非常有帮助。
我最困惑的部分是此时深度反向被调用两次
(附加 (深度反向(cdr lst)) (list (deep-reverse (car lst)))))
我不知道接下来会发生什么。
(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))))))
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))))))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我刚刚回答了这样的问题
发生的情况是,它会反转恰好是列表的每个项目,然后将其附加到列表末尾。想象一下,如果它没有对列表中的汽车调用 deep-reverse 会发生什么:
(reverse '(a (bcd) e)
isWith deep-reverse it's won't like
Which is
Here是深度反向的另一个版本,写法不同,如果这样更清楚的话,
这个版本的深度复制使用累加器并且是尾递归的,
它在将元素添加到列表之前检查它是否是一个列表,如果是。是的,首先将其反转。由于它调用自身来反转内部列表,
因此它可以处理按相反字母顺序排列的任意嵌套,尽管它的计算结果如下:
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:
很简单,您不知道头是整数还是列表,因此您还必须对其应用
deep-reverse
,然后将其附加到当前列表的反向尾部。所以:
必须变成
注意我们如何必须颠倒头部和尾部。
Easy, you don't know whether the head is an integer or a list, so you have to apply
deep-reverse
on it also, then append it to the reversed tail of the current list.So:
has to become
Notice how we had to reverse the head AND the tail.