Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to transform a seq into a tree

Tags:

clojure

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}])
like image 682
murtaza52 Avatar asked Sep 13 '13 06:09

murtaza52


1 Answers

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)

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.

You can use post-order traversal to build up another representation of the tree if desired.

like image 67
A. Webb Avatar answered Oct 16 '22 00:10

A. Webb