A simple macro to simulate ruby string interpolation
Ruby interpolation
One features that Ruby has that makes life easier is string interpolation. With string interpolation you can make your code easier on the eyes when there is a lot of string concatenation to be done:
which in clojure would look something like:
Ruby style string interpolation
Clojure unfortunately does not have string interpolation, but thanks to macros we can fix this.
We will implement a macro that looks like this:
And expands to:
Limitations:
To keep things simple, you can only enter one symbol inside #{}
, you can’t
enter complex expressions like #{(conj [1 2 3 4] 6)}
.
Also we won’t be doing escaping or other fancy things, so don’t try to do
(itp "foo #{ {bar})"
which will confuse our simple implementation.
Step one: parse the string
The first thing we need to do is to implement a function that given a string with interpolations, return an array of strings and symbols.
- Take input string and iterate through characters until you reach the end
of the string or you reach an
#{interpolation}
. - Split the string into two parts: the first part is a ‘raw’ string, the second part will be an interpolation. Parse the interpolation and extract the inner symbol.
Step two: build the macro
Having defined the parse-interpolation
function in the previous step, it is
now trivial to define our interpolation macro as follows:
Interpolation!
We now have an interpolation macro that will make our string concatenations more readable.