Skip to content

Instantly share code, notes, and snippets.

@jstejada
Created March 13, 2016 21:42
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 jstejada/a1f9f76e4404b0c7133e to your computer and use it in GitHub Desktop.
Save jstejada/a1f9f76e4404b0c7133e to your computer and use it in GitHub Desktop.
Interpolate macro in clojure
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; (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)
)
)
@fhur
Copy link

fhur commented Mar 20, 2016

Looks good. Only thing I would change:
Instead of calling load-string I would convert the match to a symbol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment