Next: , Previous: , Up: Welcome to Lisp   [Contents][Index]


16.4.9 Input and Output

So far we have done I/O implicitly, by taking advantage of the toplevel. For real interactive programs this is not likely to be enough. We look at a few functions for input and output.

The most general output function in Common Lisp is format. It takes two or more argument:

The first argument to format, ‘t’, indicates that the output is to be sent to the default place. Ordinarily, this will be the toplevel. The second argument is a string that serves as a template for output. Within this string, each ‘~A’ indicates a position to be filled, and the ‘~%’ indicates a newline. The positions are filled by the values of the remaining arguments, in order.

The standard function for input is read. When given no arguments, it reads from the default place, which is usually the toplevel. read will sit waiting indefinitely until you type soemthing and hit return.

read is a complete Lisp parser. It doesn’t just read characters and return them as a string. It parses what it reads and returns the Lisp object that results.

The body of a function can have any number of expressions. When the function is called, they will be evaluated in order, and the function will return the value of the last one.

A side-effect is some change to the state of the world that happens as a consequence of evaluating an expression. When we evaluate a pure Lisp expression like ‘(+ 1 2)’, there are no side-effects; it just returns a value. But when we call format, as well as returning a value, it prints something. That’s one kind of side-effect.

When we are writing code without side-effects, there is no point in defining functions with bodies of more than one expression. The value of the last expression is returned as the value of the function, but the values of any preceding expressions are thrown away. If such expressions don’t have side-effects, you would have no way of telling whether Lisp bothered to evaluate them at all.


Next: Variables, Previous: Reading Lisp, Up: Welcome to Lisp   [Contents][Index]