4.5.1 Printing

One useful procedure built-in to DrRacket is the display. It takes one input, and produces no output. Instead of producing an output, it prints out the value of the input (it will appear in purple in the Interactions window). We can use display to observe what a procedure is doing as it is evaluated.

For example, if we add a (display n) expression at the beginning of our factorial procedure we can see all the intermediate calls. To make each printed value appear on a separate line, we use the newline. The newline procedure prints a new line; it takes no inputs and produces no output.

(define (factorial n)
        (display "Enter factorial: ") (display n)
        (newline) (if (= n 0) 1 (* n (factorial (- n 1)))))

Evaluating (factorial 2) produces:

Enter factorial: 2
Enter factorial: 1
Enter factorial: 0
2

printingprintf The built-in printf procedure makes it easier to print out many values at once. It takes one or more inputs. The first input is a string (a sequence of characters enclosed in double quotes). The string can include special ~a markers that print out values of objects inside the string. Each ~a marker is matched with a corresponding input, and the value of that input is printed in place of the ~a in the string. Another special marker, ~n, prints out a new line inside the string.

Using printf, we can define our factorial procedure with printing as:

(define (factorial n)
        (printf "Enter factorial:  a n" n)
        (if (= n 0) 1 (* n (factorial (- n 1)))))

The display, printf, and newline procedures do not produce output values. Instead, they are applied to produce side effects. A side effect is something that changes the state of a computation. In this case, the side effect is printing in the Interactions window. Side effects make reasoning about what programs do much more complicated since the order in which events happen now matters. We will mostly avoid using procedures with side effects until Chapter 9, but printing procedures are so useful that we introduce them here.