The less-familiar parts of Lisp for beginners — read and read-preserving-whitespace

I’m going to take a brief stop here at read.  While that’s a fairly basic Lisp operation, a newcomer to Lisp might not have seen many examples where programs take input.  So, we’ll talk about read and read-preserving-whitespace a little, to point out what they are, and what they are not.

These two functions are very similar, differing only in how they treat trailing whitespace (read consumes all whitespace up to the start of the next object, or the end-of-file, while read-preserving-whitespace stops immediately after the object read).  It’s important to note, though, that they are not general-purpose input methods.  The read function consumes enough characters from its input stream to produce a single Lisp object.  It is assumed that the input stream consists of readable objects (by the definition of *print-readably*, see the earlier article on print).  These functions do not handle badly-formatted input well, raising an error if the input can’t be interpreted as a Lisp object.

If you’re writing code that reads in data files, or parses English text, you will probably not be doing it with read.  You’ll use, instead, read-line, which returns a string of all the text up to the next newline or the end of file.  You will then use string parsing techniques to interpret the stream.

Places where I have used read are in client-server command protocols.  Rather than sending bare text sequences over the channel, I send lists which contain keywords and arguments related to the information exchanged.  Since I control both ends of the connection, any read failures are related to bugs in the sending program, which I must find and fix.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.