Created
January 23, 2012 11:00
-
-
Save alandipert/1662488 to your computer and use it in GitHub Desktop.
interpolate.clj
This file contains hidden or 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. | |
;;; | |
;;; See also: https://gist.github.com/1676575 | |
(ns interpolate | |
(:use [clojure.walk :only (postwalk)]) | |
(:require [clojure.string :as string])) | |
(defmacro i | |
"This is my string interpolation macro. There are many like it, but | |
this one is #{mine}." | |
[tmpl] | |
{:pre [(string? tmpl)]} | |
(let [re #"#\{(.*?)\}"] | |
(if-let [matches (re-seq re tmpl)] | |
(list* 'format (string/replace tmpl re "%s") | |
(map (comp read-string second) matches)) | |
tmpl))) | |
(defmacro interpolating | |
"Walks body and interpolates all strings." | |
[& body] | |
`(do ~@(postwalk #(if (string? %) `(i ~%) %) body))) | |
(comment | |
(let [x 10] | |
(def y 20) | |
(println (i "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