Skip to content

Instantly share code, notes, and snippets.

@blacktaxi
Forked from alandipert/interpolate.clj
Created January 25, 2012 21:20
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 blacktaxi/1678780 to your computer and use it in GitHub Desktop.
Save blacktaxi/1678780 to your computer and use it in GitHub Desktop.
interpolate.clj
;;; ENVIRONMENTAL IMPACT STATEMENT
;;;
;;; This program was written on recycled memory.
;;; No cons cells were created.
;;;
(ns interpolate
(:use [clojure.walk :only (postwalk)]))
(defmacro s
"This is my string interpolation macro. There are many like it, but
this one is ${mine}."
[tmpl]
(let [vars (re-seq #"\$\{[^\}]*\}" tmpl)
strip #(apply str (drop 2 (butlast %)))]
(list* 'format (reduce #(.replace %1 %2 "%s") tmpl vars)
(map (comp read-string strip) vars))))
(defmacro interpolating
"Walks body and interpolates all strings."
[& body]
`(do ~@(postwalk #(if (string? %) `(s ~%) %) body)))
(comment
(let [x 10]
(def y 20)
(println (s "x is ${x}, y is ${y}, and x+y is ${(+ x y)}")))
(interpolating
(let [x 20]
(println "hey there, mr. ${x}! how ya doin?")))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment