Exercise 1.2.11
Printing With princ
When you want to send a string to a stream that's meant for your users and not the Lisp Reader, you'll want to use the princ
function. It sets the Lisp Printer parameters :escape
and :readably
to nil
, so that your users can see the string you intended, and not the string you had to type in Lisp to not break anything.
(princ "Hello, multiverse!")
(princ "My name is \"Colin\".")
As an exception to the usual rule of "Type exactly what I type", you can change my name to yours whenever it comes up in a source-code example. Just make sure it runs!
What You Should See
* (princ "Hello, multiverse!")
Hello, multiverse!
"Hello, multiverse!"
* (princ "My name is \"Colin\".")
My name is "Colin".
"My name is \"Colin\"."
Now the difference between the printed string and the return result for a function should be more clear. You can see above what setting the Lisp Printer parameters :escape
and :readably
to nil
do: it prints the characters in a string un-escaped, not printing the outer quotation marks---so your users get exactly the string you intended.
The princ
function, like the other Lisp Printer functions we've covered so far, still returns the original string object after it has been printed to a stream. This is not the case with format
, which we'll go over briefly in the next two exercises.