Last active
August 29, 2015 13:57
-
-
Save viebel/9443283 to your computer and use it in GitHub Desktop.
Clojure Macros: get-it, assoc-it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;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