Format (Common Lisp)
   HOME

TheInfoList



OR:

Format is a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
in
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
that can produce
formatted text In computing, formatted text, styled text, or rich text, as opposed to plain text, is digital text which has styling information beyond the minimum of semantic elements: colours, styles ( boldface, italic), sizes, and special features in HT ...
using a format
string String or strings may refer to: *String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects Arts, entertainment, and media Films * ''Strings'' (1991 film), a Canadian anim ...
similar to the print format string. It provides more functionality than print, allowing the user to output numbers in various formats (including, for instance: hex,
binary Binary may refer to: Science and technology Mathematics * Binary number, a representation of numbers using only two values (0 and 1) for each digit * Binary function, a function that takes two arguments * Binary operation, a mathematical op ...
,
octal Octal (base 8) is a numeral system with eight as the base. In the decimal system, each place is a power of ten. For example: : \mathbf_ = \mathbf \times 10^1 + \mathbf \times 10^0 In the octal system, each place is a power of eight. For ex ...
,
roman numerals Roman numerals are a numeral system that originated in ancient Rome and remained the usual way of writing numbers throughout Europe well into the Late Middle Ages. Numbers are written with combinations of letters from the Latin alphabet, eac ...
, and English), apply certain format specifiers only under certain conditions, iterate over
data structures In computer science, a data structure is a data organization and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, and the functi ...
, output data tabularly, and even recurse, calling format internally to handle
data structures In computer science, a data structure is a data organization and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, and the functi ...
that include their own preferred formatting strings. This functionally originates in
MIT The Massachusetts Institute of Technology (MIT) is a private research university in Cambridge, Massachusetts, United States. Established in 1861, MIT has played a significant role in the development of many areas of modern technology and sc ...
's
Lisp Machine Lisp Lisp Machine Lisp is a programming language, a dialect of the language Lisp. A direct descendant of Maclisp, it was initially developed in the mid to late 1970s as the system programming language for the Massachusetts Institute of Technology (MI ...
, where it was based on
Multics Multics ("MULTiplexed Information and Computing Service") is an influential early time-sharing operating system based on the concept of a single-level memory.Dennis M. Ritchie, "The Evolution of the Unix Time-sharing System", Communications of t ...
.


Specification

The format function is specified by the
syntax In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituenc ...
: : Directives in the control string are interpolated using the format arguments, and the thus constructed character sequence is written to the destination.


Destination

The destination may either be a
stream A stream is a continuous body of water, body of surface water Current (stream), flowing within the stream bed, bed and bank (geography), banks of a channel (geography), channel. Depending on its location or certain characteristics, a strea ...
, a dynamic
string String or strings may refer to: *String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects Arts, entertainment, and media Films * ''Strings'' (1991 film), a Canadian anim ...
, T, or the NIL constant; the latter of which presents a special case in that it creates, formats and returns a new string
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an a ...
, while T refers to the
standard output Standard may refer to: Symbols * Colours, standards and guidons, kinds of military signs * Standard (emblem), a type of a large symbol or emblem used for identification Norms, conventions or requirements * Standard (metrology), an object t ...
, usually being equivalent to the
console Console may refer to: Computing and video games * System console, a physical device to operate a computer ** Virtual console, a user interface for multiple computer consoles on one device ** Command-line interface, a method of interacting with ...
. 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 A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their syntax (form) and semantics (meaning), usually defined by a formal language. Languages usually provide features ...
, such as C's
printf printf is a C standard library function that formats text and writes it to standard output. The function accepts a format c-string argument and a variable number of value arguments that the function serializes per the format string. Mism ...
for console output, sprintf for string formatting, and
fprintf The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header . The functionality descends from a "portable I/O package" written by Mike Lesk at ...
for file writing. The multitude of destination types is exemplified in the following: ;; Prints "1 + 2 = 3" to the standard output and returns ``NIL''. (format t "1 + 2 = ~D" 3) ;; Creates and returns a new string containing "1 + 2 = 3". (format nil "1 + 2 = ~D" 3) ;; Creates and returns a new string containing "1 + 2 = 3". (with-output-to-string (output) (format output "1 + 2 = ~D" 3)) ;; Writes to the file "outputFile.txt" the string "1 + 2 = 3". (with-open-file (output "outputFile.txt" :direction :output :if-does-not-exist :create :if-exists :append) (format output "1 + 2 = ~D" 3)) ;; Appends to the dynamic string the string "1 + 2 = 3". (let ((output-string (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))) (declare (type string output-string)) (format output-string "1 + 2 = ~D" 3) (the string output-string))


Control String and Format Arguments

The control string may contain literal characters as well as the meta character ~ (
tilde The tilde (, also ) is a grapheme or with a number of uses. The name of the character came into English from Spanish , which in turn came from the Latin , meaning 'title' or 'superscription'. Its primary use is as a diacritic (accent) in ...
), which demarcates ''format directives''. While literals in the input are echoed verbatim, directives produce a special output, often consuming one or more format
arguments An argument is a series of sentences, statements, or propositions some of which are called premises and one is the conclusion. The purpose of an argument is to give reasons for one's conclusion via justification, explanation, and/or persua ...
.


Directives

A format directive, introduced by a ~, is followed by
zero 0 (zero) is a number representing an empty quantity. Adding (or subtracting) 0 to any number leaves that number unchanged; in mathematical terminology, 0 is the additive identity of the integers, rational numbers, real numbers, and compl ...
or more prefix
parameters A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
, zero or more modifiers, and the directive type. A directive definition, hence, must conform to the following pattern: : The directive type is always specified by a single character, case-insensitive in the case of letters. The
data Data ( , ) are a collection of discrete or continuous values that convey information, describing the quantity, quality, fact, statistics, other basic units of meaning, or simply sequences of symbols that may be further interpreted for ...
to be processed by a format directive, if at all necessary, is called its format argument and may be zero or more
objects Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ai ...
of any type compatible. Whether and in which quantity such data is accepted depends on the directive and potential modifiers applied unto it. The directive type ~%, for instance, abstains from the consumption of any format arguments, whereas ~D expects exactly one
integer number An integer is the number zero ( 0), a positive natural number (1, 2, 3, ...), or the negation of a positive natural number ( −1, −2, −3, ...). The negations or additive inverses of the positive natural numbers are referred to as negative ...
to print, and ~@


Example

An example of a C printf
call Call or Calls may refer to: Arts, entertainment, and media Games * Call (poker), a bet matching an opponent's * Call, in the game of contract bridge, a bid, pass, double, or redouble in the bidding stage Music and dance * Call (band), from L ...
is the following: printf("Color %s, number1 %d, number2 %05d, hex %x, float %5.2f, unsigned value %u.\n", "red", 123456, 89, 255, 3.14, 250); Using Common Lisp, this is equivalent to: (format t "Color ~A, number1 ~D, number2 ~5,'0D, hex ~X, float ~5,2F, unsigned value ~D.~%" "red" 123456 89 255 3.14 250) ;; 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 , and } directives:18. A Few FORMAT Recipes
from
Practical Common Lisp ''Practical Common Lisp'' is an introductory book on the programming language Common Lisp by Peter Seibel. It features a fairly complete introduction to the language interspersed with practical example chapters, which show developing various pieces ...
(let ((groceries '(eggs bread butter carrots))) (format t "~.~%" groceries) ; Prints in uppercase (format t "~:(~~).~%" groceries)) ; 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: (let ((template "The lucky winners were:~# none~; ~S~; ~S and ~S~ ~:;~@~")) (format nil template) ;; ⇒ "The lucky winners were: none." (format nil template 'foo) ;; ⇒ "The lucky winners were: FOO." (format nil template 'foo 'bar) ;; ⇒ "The lucky winners were: FOO and BAR." (format nil template 'foo 'bar 'baz) ;; ⇒ "The lucky winners were: FOO, BAR, and BAZ." (format nil template 'foo 'bar 'baz 'quux) ;; ⇒ "The lucky winners were: FOO, BAR, BAZ, and QUUX." ) 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. (defun mydirective (destination format-argument colon-modifier-supplied-p at-sign-modifier-supplied-p &optional (repetitions 1)) "This function represents a callback suitable as a directive in a ``format'' invocation, expecting a string as its FORMAT-ARGUMENT to print REPETITIONS number of times to the DESTINATION. --- The COLON-MODIFIER-SUPPLIED-P and AT-SIGN-MODIFIER-SUPPLIED-P flags expect a generalized Boolean each, being the representatives of the ``:'' and ``@'' modifiers respectively. Their influence is defined as follows: - If no modifier is set, the FORMAT-ARGUMENT is printed without further modifications. - If the colon modifier is set, but not the at-sign modifier, the FORMAT-ARGUMENT is converted into lowercase before printing. - If the at-modifier is set, but not the colon-modifier, the FORMAT-ARGUMENT is converted into uppercase before printing. - If both modifiers are set, the FORMAT-ARGUMENT is reversed before printing. --- The number of times the FORMAT-ARGUMENT string is to be printed is determined by the prefix parameter REPETITIONS, which must be a non-negative integer number and defaults to one." (declare (type (or null (eql t) stream string) destination)) (declare (type t format-argument)) (declare (type t colon-modifier-supplied-p)) (declare (type t at-sign-modifier-supplied-p)) (declare (type (integer 0 *) repetitions)) (let ((string-to-print format-argument)) (declare (type string string-to-print)) ;; Adjust the STRING-TO-PRINT based upon the modifiers. (cond ((and colon-modifier-supplied-p at-sign-modifier-supplied-p) (setf string-to-print (reverse string-to-print))) (colon-modifier-supplied-p (setf string-to-print (string-downcase string-to-print))) (at-sign-modifier-supplied-p (setf string-to-print (string-upcase string-to-print))) (t nil)) (loop repeat repetitions do (format destination "~A" string-to-print)))) ;; Print "Hello" a single time. (format t "~/mydirective/" "Hello") ;; Print "Hello" three times. (format t "~3/mydirective/" "Hello") ;; Print a lowercase "Hello" (= "hello") three times. (format t "~3:/mydirective/" "Hello") ;; Print an uppercase "Hello" (= "HELLO") three times. (format t "~3@/mydirective/" "Hello") ;; Print a reversed "Hello" (= "olleH") three times. (format t "~3:@/mydirective/" "Hello") 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. A Common Lisp FORMAT summary table is available.Common Lisp FORMAT summary table
/ref>


See also

*
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
*''
Common Lisp the Language ''Common Lisp the Language'' is a reference book by Guy L. Steele about a set of technical standards and programming languages named Common Lisp. History Before standardizing The first edition (Digital Press, 1984; ; 465 pages) was written by Gu ...
'' *''
Practical Common Lisp ''Practical Common Lisp'' is an introductory book on the programming language Common Lisp by Peter Seibel. It features a fairly complete introduction to the language interspersed with practical example chapters, which show developing various pieces ...
'' *''
On Lisp ''On Lisp: Advanced Techniques for Common Lisp'' is a book by Paul Graham on macro programming in Common Lisp. Published in 1993, it is currently out of print, but can be freely downloaded as a PDF Portable document format (PDF), standardiz ...
''


References


Books

*
Common Lisp HyperSpec The Common Lisp HyperSpec is a technical standard document written in the hypertext format ''Hypertext Markup Language'' (HTML). It is not the American National Standards Institute (ANSI) Common Lisp standard, but is based on it, with permission fr ...
br>Section 22.3 Formatted Output
*
Practical Common Lisp ''Practical Common Lisp'' is an introductory book on the programming language Common Lisp by Peter Seibel. It features a fairly complete introduction to the language interspersed with practical example chapters, which show developing various pieces ...
br>Chapter 18. A Few FORMAT Recipes
Common Lisp {{Improve categories, date=June 2024