【问题标题】:walk through tree functionally功能性地穿过树
【发布时间】:2013-06-22 15:17:03
【问题描述】:

我正在尝试编写自己的“遍历树”函数,但我是 FP 的新手

我写了这些函数,效果很好,但是看起来很丑

(defrecord Tree [value left right])
(defn depth_walk_tree
    [tree functor]
        (let [item (functor (:value tree))]
            (let [leftlst 
                    (if (:left tree) 
                        (cons item (depth_walk_tree (:left tree) functor)) 
                        (list item))
                 ]
                    (if (:right tree)
                        (concat 
                            leftlst 
                            (depth_walk_tree (:right tree) functor)) 
                        leftlst))))

(def tree (Tree. 1 (Tree. 2 (Tree. 0 nil nil) (Tree. 90 nil nil)) (Tree. 3 nil (Tree. 10 nil nil)) ))
    (println (depth_walk_tree tree #(+ % 1) ))

程序答案是

(2 3 1 91 4 11); is Ok

谁能告诉我如何让它变美?

PS 很抱歉我的写作错误。英语不是我的母语。

【问题讨论】:

    标签: clojure tree functional-programming


    【解决方案1】:

    这看起来更实用,恕我直言:

    (defn depth_walk_tree [tree functor]
      (concat
        (list (functor (:value tree)))
        (if (:left  tree) (depth_walk_tree (:left  tree) functor))
        (if (:right tree) (depth_walk_tree (:right tree) functor))))
    

    它也保留了原始结果:

    (depth_walk_tree tree inc)
    => (2 3 1 91 4 11)
    

    【讨论】:

    • 如此纯净!我不知道 concat 传递 'nil' 值。谢谢。
    • 函数式编程就是简单和优雅:)
    • 如何避免非尾调用递归导致的 Stack Overflow?
    • @event_jr 通过将上述内容转换为尾递归,当然 :P 。但这已经超出了重点,OP 要求的是一种惯用的、美丽 的解决方案,尾递归版本对于初学者来说会有点难以理解。这不是关于效率的问题,我怀疑 OP 是否会定义如此大的树以导致堆栈溢出,这是一个学习练习。过早的优化是万恶之源……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多