如何将嵌套映射转换为一组边

时间:2017-03-20 15:15:08

标签: graph clojure

我在嵌套地图中有一个图表,我希望将其转换为一组带有节点ID,节点标签和边缘标签的边缘:

#{{:edge/from 17592186325348 :edge/to 17592186325351 
:edge/label :A2 
:edge/from_node_label "a" :edge/to_node_label "l"}} 

在这里,我展示了在下面的数据结构中出现两次的边a->l所需的格式。数据结构以"源节点"开头。儿童编码其他目标。 :edge_label是从父级到子级的有向边的标签。

我猜测递归解决方案最简单吗?

{:db/id 17592186325353,
 :predicate/children [{:db/id 17592186325357,
                       :predicate/children [{:db/id 17592186325348,
                                             :predicate/children [{:db/id 17592186325351,
                                                                   :predicate/children [],
                                                                   :node_label "l",
                                                                   :edge_label :A1}],
                                             :node_label "a",
                                             :edge_label :A2}],
                       :node_label "m",
                       :edge_label :A2}
                      {:db/id 17592186325348,
                       :predicate/children [{:db/id 17592186325351,
                                             :predicate/children [],
                                             :node_label "l",
                                             :edge_label :A1}],
                       :node_label "a",
                       :edge_label :A1}],
 :node_label "e"}

这是一个图表,因为在a处有一个循环。 但是,出于可视化的目的,我从view-tree滥用rhizomeenter image description here

1 个答案:

答案 0 :(得分:1)

(map (partial zipmap [:edge/from :edge/to :edge/from_node_labe :edge/to_node_label :edge/label])
(mapcat (fn [a] (map (fn [a b] [(:db/id a) (:db/id b) (:node_label a) (:node_label b)  (:edge_label b)]) (repeat a) (:predicate/children a))) 
(remove (comp empty? :predicate/children) 
(tree-seq :predicate/children :predicate/children your-original-data-structure))))

给出:

({:edge/from 17592186325353,
  :edge/to 17592186325357,
  :edge/from_node_labe "e",
  :edge/to_node_label "m",
  :edge/label :A2}
 {:edge/from 17592186325353,
  :edge/to 17592186325348,
  :edge/from_node_labe "e",
  :edge/to_node_label "a",
  :edge/label :A1}
 {:edge/from 17592186325357,
  :edge/to 17592186325348,
  :edge/from_node_labe "m",
  :edge/to_node_label "a",
  :edge/label :A2}
 {:edge/from 17592186325348,
  :edge/to 17592186325351,
  :edge/from_node_labe "a",
  :edge/to_node_label "l",
  :edge/label :A1}
 {:edge/from 17592186325348,
  :edge/to 17592186325351,
  :edge/from_node_labe "a",
  :edge/to_node_label "l",
  :edge/label :A1})

我不确定它是否最简单。