Lisp quest discovering a parenthesis world

SBCL printing output twice

While learning the basics of the SBCL REPL you may have noticed its strange behaviour when it comes to the output of some instructions.

Making a sum will produce a single output with the result of the operation.

* (+ 1 5)
  6

The same will happen when calculating the square root of a number.

* (sqrt 4)
  2.0

But if we try to print a string using the print function, the result will be quite strange - an empty line followed by the same string printed twice.

* (print "twice")

  "twice"
  "twice"

In order to understand why a blank line is added to the output, we can try using another printing function called prin1. Its output is equal to print except for the missing blank line.

* (prin1 "twice")
  "twice"
  "twice"

As you can see from the functions’ documentation, the only difference between them is exactly this empy line (a new line actually) printed before the output. The print function will add it to the output, while prin1 not. But we have not yet discovered why the string is printed twice. The mystery is quite simple to solve, because the first string printed by the function is its output in the standard out. The second string is the value returned by the function and printed by the REPL - in a non-interactive program you will never see this behaviour.

If you need another prove of this behaviour you could try to assign the output of the print function to a variable (str) and then transforming it in uppercase.

* (let ((str (print "Hello, world!")))
    (string-upcase str))

  "Hello, world!"
  "HELLO, WORLD!"

Here the behaviour is clear. The blank line is added by print as the first string (the case has been kept). The last line is the uppercase version of the string, but we have not explicitly printed it. So it could have been printed only by the REPL itself - and this is the proof we were looking for.