Scheme(Lisp)中的树的深度倒转 [英] Deep-reverse for trees in Scheme (Lisp)

查看:562
本文介绍了Scheme(Lisp)中的树的深度倒转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 (define(deep-reverse t))$ b我在基本的树状数据结构中有一个深刻的反向$ b(cond((null?t)'())
((not(pair?t))t)
(else(cons(deep-reverse(cdr t) (car t))))))

(define stree(cons(list 1 2)(list 3 4)))
1] => (深反转)
;值:(((())4)3)(()2)1)

我觉得像一个更干净,更好的结果是:

 (4 3 (2 1))

任何人都可以提供一些指导,说明我在哪里错了相反的功能?谢谢。

解决方案

最好将任务分解成简单的操作,而不是一次尝试。你想要实现的可以这样描述:反转当前列表本身,然后深入反转所有的子列表(或者相反,这两个步骤的顺序并不重要,我选择这个顺序是因为它导致更好的源代码格式化)。



现在,在标准库中已经有一个功能,用于简单地反转列表, reverse 。所以你需要做的就是将它与这些子列表元素的递归相结合:

 (define(deep-revers t)
(map(lambda(x)
(if(list?x)
(深反转x)
x))
(reverse t)))


I have a deep reverse for a basic tree data structure in Scheme

(define (deep-reverse t)
  (cond ((null? t) '())
        ((not (pair? t)) t)  
        (else (cons (deep-reverse (cdr t)) (deep-reverse (car t))))))

(define stree (cons (list 1 2) (list 3 4)))
1 ]=> (deep-reverse stree)
;Value: (((() . 4) . 3) (() . 2) . 1)

I feel like a cleaner, better result would be:

(4 3 (2 1))

Can anyone provide some guidance as to where I'm going wrong in my deep-reverse function? Thank you.

解决方案

It's better to split the task into simple operations instead of trying to do all at once. What you want to achieve can be described like this: Reverse the current list itself, then deep-reverse all sublists in it (or the other way round, the order of the two steps doesn't really matter. I choose this order because it results in nicer formatting of the source code).

Now, there already is a function in the standard library for simply reversing a list, reverse. So all you need to do is to combine that with the recursion on those elements that are sublists:

(define (deep-reverse t)
  (map (lambda (x)
         (if (list? x)
             (deep-reverse x)
             x))
       (reverse t)))

这篇关于Scheme(Lisp)中的树的深度倒转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆