3

我正在尝试编写自己的“遍历树”功能,但我是 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对不起我的写作错误。英语不是我的母语。

4

1 回答 1

3

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

(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)
于 2013-06-22T15:31:07.447 回答