Skip to content

Instantly share code, notes, and snippets.

@tristanstraub
Last active February 7, 2018 00:06
Show Gist options
  • Select an option

  • Save tristanstraub/93575d5b61611dcf0535d6fade0e8034 to your computer and use it in GitHub Desktop.

Select an option

Save tristanstraub/93575d5b61611dcf0535d6fade0e8034 to your computer and use it in GitHub Desktop.

Revisions

  1. tristanstraub revised this gist Feb 7, 2018. 1 changed file with 6 additions and 8 deletions.
    14 changes: 6 additions & 8 deletions tree.clj
    Original file line number Diff line number Diff line change
    @@ -23,14 +23,12 @@
    #(if (map? %) (vals %) (seq %))
    tree)
    lookup (into {}
    (->> (vec (->> nodes
    frequencies
    (remove #(<= (second %)
    1))
    (map first)
    #_ (remove #(<= (count (with-out-str (prn %)))
    100))))
    (map #(vector % (new-id!)))))]
    (->> nodes
    frequencies
    (remove #(<= (second %) 1))
    #_ (remove #(<= (count (with-out-str (prn %)))
    100))
    (map #(vector (first %) (new-id!)))))]

    {:tree (walk/prewalk-replace lookup tree)
    :lookup (into {} (map (comp vec reverse) lookup))}))
  2. tristanstraub created this gist Feb 7, 2018.
    39 changes: 39 additions & 0 deletions tree.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    (ns trees
    (:require [clojure.walk :as walk]))

    (defonce id (atom 0))

    (defrecord Ref [id])

    (defn new-id! []
    (->Ref (swap! id inc)))

    (defmethod print-method Ref [this ^java.io.Writer w]
    (.write w "#ref")
    (.write w " ")
    (print-method (:id this) w))

    (defn hydrate
    [{:keys [tree lookup]}]
    (walk/prewalk-replace lookup tree))

    (defn dehydrate
    [tree]
    (let [nodes (tree-seq coll?
    #(if (map? %) (vals %) (seq %))
    tree)
    lookup (into {}
    (->> (vec (->> nodes
    frequencies
    (remove #(<= (second %)
    1))
    (map first)
    #_ (remove #(<= (count (with-out-str (prn %)))
    100))))
    (map #(vector % (new-id!)))))]

    {:tree (walk/prewalk-replace lookup tree)
    :lookup (into {} (map (comp vec reverse) lookup))}))

    #_ (prn (dehydrate {:a {:b 2} :x [{:b 2}]}))
    #_ (prn (hydrate (dehydrate {:a {:b 2} :x [{:b 2}]})))