Lisp - Formatting with Format Function



format function in LISP is a very powerful function to generate formatted output. format function allows to control the presentation of various data types.

Syntax

(format destination control-string &rest format-arguments)

Where−

  • destination− it represents the target where output should be redirected. Accepted values are t and nil. In case of nil, output is redirected to a string otherwise it is redirected to standard output. We can redirect the output to stream or a string with fill pointer as well.

  • control-string− control string contains the directives which dictates how format-arguments are to be displayed.

  • format-arguments− values to be formatted.

control-string directives

Control string starts with tilde (~) to introduce format directives. Using these directives, format function formats the arguments. Following is the description of commonly used control string directives.

  • ~A− prints the passed argument in human readable format.

  • ~S− prints the passed argument in s-expression form, a lisp readable format.

  • ~D− prints the passed argument as decimal number.

  • ~F− prints the passed argument as floating point number.

  • ~%− prints a newline character.

  • ~B− print the passed argument in binary format.

  • ~X− print the passed argument in hexadecimal format.

Example - Formatting a String to standard output

; print 1 + 2 = 3 on console
(format t "1 + 2 = ~D" 3)

Output

When you execute the code, it returns the following result −

1 + 2 = 3

Example - Formatting a String to String

; get a formatted string
(defvar expr (format nil "1 + 2 = ~D" 3))

; print the expression
(print expr)

Output

When you execute the code, it returns the following result −

"1 + 2 = 3" 

Example - Formatting a number to Binary

; print 101 on console
(format t "~B" 5)

Output

When you execute the code, it returns the following result −

101

Adding padding to a number

We can use prefix parameters in format function to add padding. Consider following case, where we need to left pad a binary representation of an integer say 5 with eight digits with zero.

; print 00000101 on console
(format t "~8,'0b" 5)

Output

When you execute the code, it returns the following result −

00000101
Advertisements