Skip to content

Instantly share code, notes, and snippets.

@lantiga
Last active October 11, 2015 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lantiga/3897862 to your computer and use it in GitHub Desktop.
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)
(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