String Formatting in Lisp
Our first program demonstrates string formatting in Lisp. Here’s the full source code with explanations:
To run the program, save it as string-formatting.lisp
and use your Lisp implementation to load and execute it. For example, with SBCL:
This example demonstrates various string formatting techniques in Lisp:
We use the format
function for all our formatting needs. It’s a powerful and flexible function in Lisp.
The ~a
directive is used for aesthetic printing, ~s
for standard printing (which includes quotes for strings), and ~%
for newlines.
For integers, ~d
is used for decimal, ~b
for binary, ~c
for character, and ~x
for hexadecimal representation.
Floats can be formatted using ~f
for fixed-point notation and ~e
or ~E
for exponential notation.
Width specifications can be added to control the field width and precision. For example, ~6d
specifies a field width of 6 for integers.
Left-justification can be achieved using the @<
and >
modifiers.
The format
function can write to different streams. By default, it writes to t
(standard output), but we can also write to files or strings.
This Lisp code provides equivalent functionality to the original Go example, demonstrating Lisp’s powerful string formatting capabilities.