Is there a way in Lisp to format a string using named parameters?
Perhaps something with association lists like
(format t "All for ~(who)a and ~(who)a for all!~%" ((who . "one")))
in order to print "All for one and one for all"
.
Similar to this python question, or this scala one, or even c++, but in Lisp.
If this functionality isn't in the language, does anyone have any cool functions or macros that could accomplish the same thing?
Use CL-INTERPOL.
String interpolation
For simple cases, you don't need
FORMAT
:Then:
Interpret format directives
If you need to format, you can do:
For example, this expression:
... prints:
If you are curious, the above reads as:
Alternate reader function
Previously, I globally set
*interpolate-format-directives*
, which interprets format directive in all interpolated strings. If you want to control precisely when format directives are interpolated, you can't just bind the variable temporarily in your code, because the magic happens at read-time. Instead, you have to use a custom reader function.If I reset the special variable to its default value NIL, then strings where directives are formatted are prefixed with
#F
, whereas normal interpolated ones use the#?
syntax. If you want to change readtables, have a look at named readtables.