Skip to content

Instantly share code, notes, and snippets.

@xfthhxk
Last active August 22, 2024 10:50
Show Gist options
  • Save xfthhxk/3e20bf378e01e2a9f62e30876e24dacc to your computer and use it in GitHub Desktop.
Save xfthhxk/3e20bf378e01e2a9f62e30876e24dacc to your computer and use it in GitHub Desktop.
Clojure transients
;; get, get-in, keyword accessor, destructuring etc all work as expected
(get-in (transient {:a (transient {:b 2})}) [:a :b]) ;; => 2
(get-in (transient {:a {:b 2}}) [:a :b]) ;; => 2
(get-in (transient {:a (transient {:b (transient [10 11 12])})}) [:a :b 1]) ;; => 11
((transient {:a 1}) :a) ;; => 1
(:a (transient {:a 1})) ;; => 1
(let [{:keys [a b]} (transient {:a 1 :b 2})]
[a b]) ;; => [1 2]
(defn assoc-in!
[coll [k & ks] v]
(if ks
(assoc! coll k (assoc-in! (get coll k) ks v))
(assoc! coll k v)))
(defn update-in!
([m ks f & args]
(let [up (fn up [m ks f args]
(let [[k & ks] ks]
(if ks
(assoc! m k (up (get m k) ks f args))
(assoc! m k (apply f (get m k) args)))))]
(up m ks f args))))
(defn update!
([m k f]
(assoc! m k (f (get m k))))
([m k f x]
(assoc! m k (f (get m k) x)))
([m k f x y]
(assoc! m k (f (get m k) x y)))
([m k f x y z]
(assoc! m k (f (get m k) x y z)))
([m k f x y z & more]
(assoc! m k (apply f (get m k) x y z more))))
(-> (transient {:a (transient {:b 2})})
(assoc-in! [:a :b] 3)
(update! :a persistent!)
persistent!) ;; => {:a {:b 3}}
(-> (transient {:a (transient {:b (transient [10 11 12])})})
(update-in! [:a :b 1] #(* % %))
(update-in! [:a :b] persistent!)
(update! :a persistent!)
persistent!) ;; => {:a {:b [10 121 12]}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment