方案的深度反转 [英] deep-reverse for scheme
本文介绍了方案的深度反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当进入((1 2) (3 4))的列表时,我想反转它,但不是这样的((3 4) (1 2)),这就是reverse的作用,所以我尝试编写一个深度反向过程:
When entering the list of ((1 2) (3 4)), I want to reverse it, but not so it's ((3 4) (1 2)), which is what reverse does, so I'm trying to write a deep-reverse procedure:
(define (deep-reverse l)
(cond ((null? l) nil)
(not (pair? (car l)) l)
(else (append (deep-reverse (cdr l)) (list (car l))))))
但它只是返回 ((1 2) (3 4)).出了什么问题,我该如何让它发挥作用?
but it just throws back ((1 2) (3 4)). What's wrong and how do I get this to work?
推荐答案
尝试:
(define (deep-reverse l) (map reverse l))
以上是最简单的答案;真正的答案取决于您期望深度反向做什么.请参阅我对您的问题的评论.
The above is the simplest possible answer; a real answer depends on exactly what you expect deep-reverse to do. See my comment to your question.
如果你想要一切,一路向下:
If you want everything, all the way down:
(define (deep-reverse l)
(if (list? l)
(reverse (map deep-reverse l))
l))
这是它的工作原理(正确):
Here is how it works (correctly):
> (deep-reverse '(1 2 ((3.1 3.2) (4) "abc")))
(("abc" (4) (3.2 3.1)) 2 1)
这篇关于方案的深度反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文