Skip to content

Instantly share code, notes, and snippets.

@devn
Last active December 5, 2022 15:02
Show Gist options
  • Save devn/b195dbc67a320021057c to your computer and use it in GitHub Desktop.
Save devn/b195dbc67a320021057c to your computer and use it in GitHub Desktop.
Recursively transform a nested map into transients, and then back to persistents
(require '[clojure.walk :as walk])
;; => nil
(defn transient? [x]
(instance? clojure.lang.ITransientCollection x))
;; => #'user/transient?
(let [transients (walk/postwalk (fn [x]
(if (map? x)
(transient x)
x))
{:a 1 :b {:c 3 :d {:e 4 :f {:g 6}}}})]
(walk/prewalk (fn [x]
(if (transient? x)
(persistent! x)
x))
transients))
;; => {:a 1, :b {:c 3, :d {:e 4, :f {:g 6}}}}
;; This takes ~0.03 msec
(let [transients (-> {:a 1 :b {:c 3 :d {:e 4 :f {:g 6}}}}
(update-in [:b :d :f] transient)
(update-in [:b :d] transient)
(update-in [:b] transient)
(transient))]
(-> transients
(persistent!)
(update-in [:b] persistent!)
(update-in [:b :d] persistent!)
(update-in [:b :d :f] persistent!)))
;; => {:a 1, :b {:c 3, :d {:e 4, :f {:g 6}}}}
;; This takes ~0.01 msec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment