Skip to content

Instantly share code, notes, and snippets.

@viebel
Last active August 29, 2015 13:57
Show Gist options
  • Save viebel/9443283 to your computer and use it in GitHub Desktop.
Save viebel/9443283 to your computer and use it in GitHub Desktop.
Clojure Macros: get-it, assoc-it
;;First rule of macros: Don't write a macro if you a function can do the job!
(defn assoc-it[obj & more]
(let [path (vec (drop-last 1 more))
val (last more)]
(assoc-in obj path val)))
(assoc-it {:a {:b 6}} :a :b 5 ) ;; {:a {:b 5}}
(defn get-it[obj & path]
(get-in obj path))
(get-it {:a {:b 3}} :a :b ) ;; 3
(defmacro assoc-it[obj & more]
`(let [path# (vec (drop-last 1 (list ~@more)))
val# (last (list ~@more))]
(assoc-in ~obj path# val#)))
(assoc-it {:a {:b 6}} :a :b 5 ) ;; {:a {:b 5}}
(defmacro get-it[obj & path]
`(get-in ~obj [~@path]))
(get-it {:a {:b 3}} :a :b ) ;; 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment