Skip to content

Instantly share code, notes, and snippets.

@ilazarte
Last active December 22, 2015 21:19
Show Gist options
  • Save ilazarte/6532704 to your computer and use it in GitHub Desktop.
Save ilazarte/6532704 to your computer and use it in GitHub Desktop.
Combining the let and map form in a macro. Declare as many bindings as you want, and it will map across them using the symbols. Came to me when I needed something like a "foreach" for templating in Hiccup, but usable in a general context as well. Obviously the macro doesn't generate too much different, but I think its easier on the eyes.
;=> (let-map [i (range 5)] (inc i))
;(1 2 3 4 5)
;=> (def books '({:name "The Great Gatsby" :href "urlA"}
; {:name "The Unbearable Lightness of Being" :href "urlB"}))
;=> (let-map [b books] [:li [:a {:href (:href b)} (:name b)]])
;([:li [:a {:href "urlA"} "The Great Gatsby"]] [:li [:a {:href "urlB"} "The Unbearable Lightness of Being"]])
(defmacro let-map
[decl form]
"Usage: (let-map [i (range 5)] (inc i))"
(let [bindings (take-nth 2 decl)
colls (take-nth 2 (rest decl))]
`(map (fn [~@bindings] ~form) ~@colls)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment