我试着写自己的“走过树”功能,但我是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对不起我的写作错误。英语不是我的母语。
答案 0 :(得分: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)