Created
March 13, 2016 21:42
-
-
Save jstejada/a1f9f76e4404b0c7133e to your computer and use it in GitHub Desktop.
Interpolate macro in clojure
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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; (itp "Fooo #{x} #{bar}") | |
; (str "Foooo" x " " bar) | |
(require '[clojure.string :as str]) | |
(defn make-result | |
[re string] | |
(let | |
[ | |
matches (re-seq re string) | |
] | |
(loop | |
[ | |
exprs (map (fn [match] `(load-string ~(get match 1))) matches) | |
strs (str/split string re) | |
res [] | |
] | |
(if (and (= (count strs) 0) (= (count exprs) 0)) | |
(into [] res) | |
(recur | |
(rest exprs) | |
(rest strs) | |
(concat res (remove nil? [(first strs) (first exprs)]))) | |
) | |
) | |
) | |
) | |
(defmacro itp | |
[string] | |
(let | |
[ | |
re #"\#\{(.*?)\}" | |
result (make-result re string) | |
] | |
`(apply str ~result) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good. Only thing I would change:
Instead of calling
load-string
I would convert the match to asymbol
.