Lisp - Interactive I/O



Interactive I/O is a fundamental capabilities of LISP for its interactive interface, REPL. In this chapter, we'll discuss the key concepts related to I/O and various types of methods available in LISP for I/O.

Core Concepts

Stream

A stream is a flow of data from a source to destination. LISP I/O uses concept of Stream heavily. A stream can be connected to various types of devices including−

  • Standard Input, generally a keyboard.

  • Standard Output, generally a display.

  • Files on underlying file system

  • Network connections

  • Strings as in memory buffers

Standard Streams

Following are standard streams for commonly used I/O operations.

  • *STANDARD-INPUT*− default input stream, generally a keyboard.

  • *STANDARD-OUTPUT*− default output stream, generally a display.

  • *TERMINAL-IO*− a bidirectional stream for interactive communication with a terminal.

Core Functions

Input Functions

  • read− most commonly used function to read a lisp object from a stream.

  • read-line− used to read a line from an input stream.

  • read-char− used to read a single character from an input stream.

  • listen− used to check if a stream has any character available to read.

Output Functions

  • print− used to print a Lisp object to output stream with a newline character.

  • princ− used to print a Lisp object to output stream without a newline character.

  • write− used to write a Lisp object to an output stream.

  • write-char− used to write a character to an output stream.

  • format− used to format the arguments and print them to an output stream.

Interactive Development

LISP provides REPL, a Read Eval Print Loop terminal which is a fundamental and powerful interface. In LISP, a REPL performs the following:

  • Read− used to read a LISP expression.

  • Eval− terminal evaluates the LISP expression.

  • Print− the result is printed.

  • Loop− terminal gets ready to read next expression.

A REPL terminal is perfect for rapid prototyping, testing and experimentation.

File I/O

In order to work with Files, LISP provides following functions.

  • open− used to open a file for read/write or to create a stream associated with a file.

  • close− used to close the stream.

Error handling

Error handling is an important aspect while performing I/O. LISP provides various options to handle end-of-file conditions and other potential errors. We should close a stream after use to prevent any resource leak.

Conclusion

LISP I/O system is quite flexible and powerful. It supports both interactive as well as file based operations.

Advertisements