Last active
October 11, 2015 17:58
-
-
Save lantiga/3897862 to your computer and use it in GitHub Desktop.
let-map macro (creating a map using a let form) and map-let (using a map to establish local bindings in a let form)
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
(defmacro let-map | |
"Takes a binding form (as in let) and returns a map of (keywordized) | |
binding names and bound values. It allows to construct a map sequentially. | |
Usage: | |
(let-map [a 1 b (+ a 1)]) | |
=> {:a 1 :b 2}" | |
[kv] | |
(let [ks (map keyword (take-nth 2 kv))] | |
`(let [~@kv] | |
(into {} (map vec (partition 2 (interleave '~ks (take-nth 2 ~kv)))))))) | |
(defmacro map-let | |
[m body] | |
"Takes a map literal and a body, evaluates body within a let form with local bindings | |
from each key of the map to its value (where binding names are un-keywordized). | |
Usage: | |
(map-let {:a 1 :b 2} [a b (+ a b)]) | |
=> [1 2 3]" | |
(let [ks (vec (map (comp symbol name) (keys m)))] | |
`(let [{:keys ~ks} ~m] ~body))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment