Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created January 23, 2012 11:00
Show Gist options
  • Save alandipert/1662488 to your computer and use it in GitHub Desktop.
Save alandipert/1662488 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.
;;;
;;; 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