-
-
Save blacktaxi/1678780 to your computer and use it in GitHub Desktop.
interpolate.clj
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
;;; 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