如何将seq转换为树 [英] how to transform a seq into a tree
本文介绍了如何将seq转换为树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一系列地图,如下面的coll。我想安排在树上。每个地图都有一个名为:parent的键,它是:父的id。任何提示如何我能做到吗?
I have a seq of maps such as the coll below. I want to arrange it in a tree. Each map has a key named :parent which is the :id of the parent. Any hints on how can I do it ?
(def coll [{:id 1}
{:id 2 :parent 1}
{:id 3 :parent 1}
{:id 4 :parent 2}
{:id 5 :parent 4}
{:id 6 :parent 5}
{:id 7 :parent 5}
{:id 8 :parent 5}
{:id 9 :parent 7}])
推荐答案
如果它像树一样走...
If it walks like a tree...
(require '[clojure.zip :as z])
(defn create-zipper [s]
(let [g (group-by :parent s)]
(z/zipper g #(map :id (g %)) nil (-> nil g first :id))))
(def t (create-zipper coll)) ; using the coll defined in the OP
(-> t z/root)
;=> 1
(-> t z/children)
;=> (2 3)
(-> t z/next z/children)
;=> (4)
请注意,您可以保留原始节点的格式)通过使用#(g(%:id))
作为子项和(first(g nil))
Note that you may preserve the format of the original nodes (rather than just returning id numbers) by using #(g (% :id))
as the children and (first (g nil))
as the root.
您可以使用 post-order遍历,以根据需要构建树的另一个表示。
You can use post-order traversal to build up another representation of the tree if desired.
这篇关于如何将seq转换为树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文