Format (Common Lisp)

Streams in Common Lisp comprehend, among others, string output and file streams; hence, being capable of writing to such a variety of destinations, this function unifies capabilities distributed among distinct commands in some other programming languages, such as C's printf for console output, sprintf for string formatting, and fprintf for file writing.

While literals in the input are echoed verbatim, directives produce a special output, often consuming one or more format arguments.

The following directive, ~B, expects one number object from the format arguments and writes its binary (radix 2) equivalent to the standard output.

Given this simple scenario, in order to left-pad a binary representation of the integer number 5 to at least eight digits with zeros, the literal solution is as follows: The first prefix parameter controlling the output width may, however, be defined in terms of the V character, delegating the parameter value specification to the next format argument, in our case 8.

The following example illustrates a rather mild case of influence exerted upon a directive by the @ modifier: It merely ensures that the binary representation of a formatted number is always preceded by the number's sign: An enumeration of the format directives, including their complete syntax and modifier effects, is adduced below.

A yet more complex example would be printing out a list using customary English phrasing: The ability to define a new directive through ~/functionName/ provides the means for customization.

The next example implements a function which prints an input string either in lowercase, uppercase or reverse style, permitting a configuration of the number of repetitions, too.

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 specialized and common need.