Print and its kin are useful basic printing functions, but for sophisticated and easy to read output, format is more useful.
The basic structure of a format call is
The full use of a destination will be introduced further below; for most basic uses, the destination should be specified as t or nil. The control string is a string containing characters to be printed, as well as control sequences. Every control sequence begins with a tilde:(format <destination> <control-string> <optional-arguments> )
~
. The control sequences may require extra arguments to be evaluated, which must be provided as optional arguments to format.
With t as the specified destination, and no control sequences in the control-string, format outputs the string in a manner similar to princ, and returns nil.
With nil as destination and no control sequences, format simply returns the string:> (format t "this") this NIL
Inserting> (format nil "this") "this"
~
% in the control string causes a newline to be output:
> (format t "~%This shows ~%printing with ~%newlines.~%") This shows printing with newlines. NIL
~
s indicates that an argument is to be evaluated and the result inserted at that point. Each ~
s in the control string must match up to an optional argument appearing after the control string.
Here is an example of a function that uses this capability:
(Float converts a number from integer or ratio to a floating point number, i.e. one with a decimal point.)(defun f-to-c (ftemp) (let ((ctemp (* (- ftemp 32) 5/9))) (format t "~%~s degrees Fahrenheit is ~%~s degrees Celsius~%" ftemp ;; first ~s (float ctemp)) ;; second ~s ctemp)) ;; return ratio value
Format simply evaluates the optional arguments in order they appear to determine the values for each> (f-to-c 82) 82 degrees Fahrenheit is 27.777777777777777 degrees Celsius 250/9
~
s. There must be enough optional arguments following the control string to provide values for all the occurrences of ~
s in the control string, otherwise an error will occur. If there are too many optional arguments, format evaluates them all (so side effects may occur) but no error is signalled.
Format will also preserve newlines entered directly in the control string. For example, f-to-c would behave just the same if defined as follows:
In addition to these two control sequences it is useful to know about(defun f-to-c (ftemp) (let ((ctemp (* (- ftemp 32) 5/9))) (format t " ~s degrees Fahrenheit is ~s degrees Celsius " ftemp (float ctemp)) ;; print floated value ctemp)) ;; return ratio value
~
T to produce tab spacing and ~
~
to print a tilde. Some other control sequences are documented in the appendix entry for format.
© Colin Allen & Maneesh Dhagat