Printing

When you evaluate a Lisp procedure in the Listener it returns a value. But when you're running a program you might want it to print out several values before the program returns a final result. Lisp provides several alternative functions specifically for printing out values. 

Printing a result: print

The simplest of these is print - it simply prints out a printed representation of its argument, and then returns the argument. So if you evaluate, for example:

CL-USER 1 > (print 123)
123 
123
The first "123" is the effect of the print procedure. The second "123" is the value returned by the procedure, which is also 123. This example makes it a bit clearer:
(defun print-and-double (n) (print n) (* n 2))

If we evaluate it we get:

CL-USER 3 > (print-and-double 12)
12 
24

Printing formatted values: format

The Swiss army knife of printing is format. It includes options for printing every type of value in every conceivable way, and I would guess that most Lisp programmers only use a small subset of its capabilities. I'll just cover its most useful features here:

The format procedure takes two or more parameters.

The first parameter is either t, to tell the format procedure to print the result, or nil, to return the result as a string.

The second parameter is a format string, which tells the format procedure how to print the result. This is a text string which can include special format sequences, prefixed by a "~" character (called a "tilde" or "twiddle"), to insert values in this string.

The remaining parameters are evaluated to give the values to be inserted into the format string. The most general format sequence is "~a" which inserts the value as it would be printed by print. So, for example:

(format t "The answer is ~a." (* 2 3))

inserts the value of (* 2 3) into the string specified by the ~a, and prints:

The answer is 6.

You can also include ~% in the format string to give a line break.

Alternatively, by specifying the second parameter as nil we can use format to generate a string for us, so:

(format nil "The answer is ~a." (* 2 3))

will return:

"The answer is 6."

There are more examples of using format in the Animals project.

Exercises

1. Use format to write a story-writing program. The procedure story should take a name, food, and colour; for example:

(story "Lisa" "cheese" "green")

and produce a story like:

There once was a princess called Lisa who liked cheese. One day Lisa found some green cheese and ate so much that she died. The end.


Previous: Strings

Next: Testing a Result


blog comments powered by Disqus