Printing Multiple Lines of Output

Common Lisp has two different commands for starting a new line during printing. The first, terpri, simply tells Lisp to terminate the current line and start a new one for printing subsequent output. For example, we can print two numbers on different lines like so:

> (progn (princ 22)
         (terpri)
         (princ 33))
22
33

We can also start a new line with fresh-line. This command will start a new line, but only if the cursor position in the REPL isn’t already at the very front of a line. Let’s look at some examples:

> (progn (princ 22)
         (fresh-line)
         (princ 33))
22
33
> (progn (princ 22)
         (fresh-line)
         (fresh-line)
         (princ 33))
22
33

As you can see, placing two fresh-line statements between the two princ calls resulted in Lisp printing only one line between the outputted numbers. The first fresh-line starts a new line; the second fresh-line is simply ignored.

Essentially, the terpri command says “start a new line,” whereas the fresh-line command says “start a new line, if needed.” Any code using the terpri command needs to “know” what was printed before. Otherwise, unsightly empty lines may result. Since it’s always better if different parts of a program know as little about each other as possible, most Lispers prefer using fresh-line over terpri, because it allows them to decouple the printing of one piece of data from the next.

The format command has two control sequences that are analogous to terpri and fresh-line:

˜%

causes a new line to be created in all cases (like terpri)

˜&

creates new lines only as needed (like fresh-line).

These examples illustrate this difference:

> (progn (format t "this is on one line ˜%")
           (format t "˜%this is on another line"))
  this is on one line

  this is on another line
  > (progn (format t "this is on one line ˜&")
           (format t "˜&this is on another line"))
  this is on one line
  this is on another line

As you can see, using an extra ˜% prints an unsightly empty line , and using ˜& in the same places does not.

These two line-termination sequences can also have an additional parameter in front of them to indicate the number of new lines to be created. This is useful in cases where we want to use empty lines to space out our output. For example, the addition of 5 in the following example adds five empty lines to our output:

> (format t "this will print ˜5%on two lines spread far apart")
this will print




on two lines spread far apart
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.147