Skip to content

Instantly share code, notes, and snippets.

@cqfd
Created June 5, 2012 22:37
Show Gist options
  • Save cqfd/2878571 to your computer and use it in GitHub Desktop.
Save cqfd/2878571 to your computer and use it in GitHub Desktop.
Reducing some stuff into a tree
(defrecord Tree [id pid children])
(def comments [{:id 1 :pid 0}
{:id 2 :pid 1}
{:id 3 :pid 1}
{:id 4 :pid 3}
{:id 5 :pid 3}
{:id 6 :pid 3}
{:id 7 :pid 2}
{:id 8 :pid 7}])
(defn tree-insert [x t]
(if (= (:pid x) (:id t))
(assoc t :children (conj (:children t) x))
(assoc t :children (map (partial tree-insert x) (:children t)))))
(tree-insert (Tree. 2 1 nil) (tree-insert (Tree. 1 0 nil) (Tree. 0 nil nil)))
(def the-tree
(reduce (fn [t x]
(tree-insert x t))
(map map->Tree comments)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment