Format (Common Lisp)
Encyclopedia
Format is a function in Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

 that can produce formatted text and is normally used in a manner analogous to printf
Printf
Printf format string refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a method for rendering an arbitrary number of varied data type parameter into a string...

 in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 and other curly bracket programming languages. However, it provides much 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.

Example

An example of a C printf call 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)
;; ⇒ 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 used using the ~{, ~^ and ~} directives:

(let ((groceries '(eggs bread butter carrots)))
(format t "~{~A~^, ~}.~%" groceries) ; Prints in uppercase
(format t "~@(~{~A~^, ~}~).~%" groceries)) ; Capitalizes output
;; ⇒ EGGS, BREAD, BUTTER, CARROTS.
;; ⇒ Eggs, bread, butter, carrots.

Books

  • Common Lisp HyperSpec
    Common Lisp HyperSpec
    The Common Lisp HyperSpec is a hypertext html document which is not the ANSI Common Lisp standard, but is based on it with permission from ANSI and X3. It is copyrighted by LispWorks Ltd...

     Section 22.3 Formatted Output
  • Practical Common Lisp
    Practical Common Lisp
    Practical Common Lisp is an introductory book on Common Lisp by Peter Seibel which intersperses "practical" chapters along with a fairly complete introduction to the language...

    Chapter 18. A Few FORMAT Recipes
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK