Format (Common Lisp)


Format is a function in Common Lisp that can produce formatted text using a format string similar to the printf format string. It provides more functionality than printf, allowing the user to output numbers in English, apply certain format specifiers only under certain conditions, iterate over data structures, and output in a tabular format. This functionally originates in MIT's Lisp Machine Lisp, where it was based on Multics ioa_.

Example

An example of a C printf call is the following:

printf;

Using Common Lisp, this is equivalent to:


;; prints: Color red, number1 123456, number2 00089, hex FF, float 3.14, unsigned value 250.

Another example would be to print every element of list delimited with commas, which can be done using the directives:


; Prints in uppercase
) ; Capitalizes output
;; prints: EGGS, BREAD, BUTTER, CARROTS.
;; prints: Eggs, Bread, Butter, Carrots.

Note that not only is the list of values iterated over directly by format, but the commas correctly are printed between items, not after them. A yet more complex example would be printing out a list using customary English phrasing:

)

;; ⇒ "The lucky winners were: none."

;; ⇒ "The lucky winners were: FOO."

;; ⇒ "The lucky winners were: FOO and BAR."

;; ⇒ "The lucky winners were: FOO, BAR, and BAZ."

;; ⇒ "The lucky winners were: FOO, BAR, BAZ, and QUUX."
)

Whilst format is somewhat infamous for its tendency to become opaque and hard to read, it provides a remarkably concise yet powerful syntax for a specialised and common need.
A Common Lisp FORMAT summary table is available.

Books