Format (Common Lisp)

From Wikipedia, the free encyclopedia
Jump to: navigation, search

Format is a function in Common Lisp that can produce formatted text and is normally used in a manner analogous to printf in C 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.


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 done using the ~{, ~^ and ~} directives:[1]

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


  1. ^ 18. A Few FORMAT Recipes from Practical Common Lisp