-
- Introduction
- Purpose
- Commonality
- Common Lisp originated in an attempt to focus the work of several implementation groups, each of which was constructing successor implementations of MacLisp for different computers. These implementations had begun to diverge because of the differences in the implementation environments: microcoded personal computers (Zetalisp, Spice Lisp), commercial timeshared computers (NIL-the ``New Implementation of Lisp''), and supercomputers (S-1 Lisp). While the differences among the several implementation environments of necessity will continue to force certain incompatibilities among the implementations, Common Lisp serves as a common dialect to which each implementation makes any necessary extensions.
- Portability
- Common Lisp intentionally excludes features that cannot be implemented easily on a broad class of machines. On the one hand, features that are difficult or expensive to implement on hardware without special microcode are avoided or provided in a more abstract and efficiently implementable form. (Examples of this are the invisible forwarding pointers and locatives of Zetalisp. Some of the problems that they solve are addressed in different ways in Common Lisp.) On the other hand, features that are useful only on certain ``ordinary'' or ``commercial'' processors are avoided or made optional. (An example of this is the type declaration facility, which is useful in some implementations and completely ignored in others. Type declarations are completely optional and for correct programs affect only efficiency, not semantics.) Common Lisp is designed to make it easy to write programs that depend as little as possible on machine-specific characteristics, such as word length, while allowing some variety of implementation techniques.
- Consistency
- Most Lisp implementations are internally inconsistent in that by default the interpreter and compiler may assign different semantics to correct programs. This semantic difference stems primarily from the fact that the interpreter assumes all variables to be dynamically scoped, whereas the compiler assumes all variables to be local unless explicitly directed otherwise. This difference has been the usual practice in Lisp for the sake of convenience and efficiency but can lead to very subtle bugs. The definition of Common Lisp avoids such anomalies by explicitly requiring the interpreter and compiler to impose identical semantics on correct programs so far as possible.
- Expressiveness
- Common Lisp culls what experience has shown to be the most useful and understandable constructs from not only MacLisp but also Interlisp, other Lisp dialects, and other programming languages. Constructs judged to be awkward or less useful have been excluded. (An example is the store construct of MacLisp.)
- Compatibility
- Unless there is a good reason to the contrary, Common Lisp strives to be compatible with Lisp Machine Lisp, MacLisp, and Interlisp, roughly in that order.
- Efficiency
- Common Lisp has a number of features designed to facilitate the production of high-quality compiled code in those implementations whose developers care to invest effort in an optimizing compiler. One implementation of Common Lisp, namely S-1 Lisp, already has a compiler that produces code for numerical computations that is competitive in execution speed to that produced by a Fortran compiler [11]. The S-1 Lisp compiler extends the work done in MacLisp to produce extremely efficient numerical code [19].
- Power
- Common Lisp is a descendant of MacLisp, which has traditionally placed emphasis on providing system-building tools. Such tools may in turn be used to build the user-level packages such as Interlisp provides; these packages are not, however, part of the Common Lisp core specification. It is expected such packages will be built on top of the Common Lisp core.
- Stability
- It is intended that Common Lisp will change only slowly and with due deliberation. The various dialects that are supersets of Common Lisp may serve as laboratories within which to test language extensions, but such extensions will be added to Common Lisp only after careful examination and experimentation.
- Notational Conventions
- Decimal Numbers
- Nil, False, and the Empty List
- the symbol nil is used to represent both the empty list and the ``false'' value for Boolean tests
- Any data object other than nil is construed to be Boolean ``not false'', that is, ``true''
- Evaluation, Expansion, and Equivalence
- Execution of code in Lisp is called evaluation because executing a piece of code normally results in a data object called the value produced by the code. The symbol => is used in examples to indicate evaluation. For example,
- The symbol -> is used in examples to indicate macro expansion. For example,
- (push x v) -> (setf v (cons x v))
- The symbol == is used in examples to indicate code equivalence. For example,
- (gcd x (gcd y z)) == (gcd (gcd x y) z)
- Errors
- ``is an error'' for some situation to occur, this means that:
- No valid Common Lisp program should cause this situation to occur.
- If this situation occurs, the effects and results are completely undefined as far as adherence to the Common Lisp specification is concerned.
- No Common Lisp implementation is required to detect such an error. Of course, implementors are encouraged to provide for detection of such errors wherever reasonable.
- ``an error is signaled,'' this means that:
- If this situation occurs, an error will be signaled (see error and cerror).
- Valid Common Lisp programs may rely on the fact that an error will be signaled.
- Every Common Lisp implementation is required to detect such an error.
- Descriptions of Functions and Other Entities
- The Lisp Reader
- Overview of Syntax
- (
- A left parenthesis begins a list of items. The list may contain any number of items, including zero. Lists may be nested. For example, (cons (car x) (cdr y)) is a list of three things, of which the last two are themselves lists.
- )
- A right parenthesis ends a list of items.
- '
- An acute accent (also called single quote or apostrophe) followed by an expression form is an abbreviation for (quote form). Thus 'foo means (quote foo) and '(cons 'a 'b) means (quote (cons (quote a) (quote b))).
- ;
- Semicolon is the comment character. It and all characters up to the end of the line are discarded.
- "
- Double quotes surround character strings:
- "This is a thirty-nine-character string."
- \
- Backslash is an escape character.
- A\(B denotes a symbol whose name consists of the three characters A, (, and B.
- advanced
- :
- Colon is used to indicate which package a symbol belongs to. For example, network:reset denotes the symbol named reset in the package named network. A leading colon indicates a keyword, a symbol that always evaluates to itself. The colon character is not actually part of the print name of the symbol. This is all explained in chapter 11; until you read that, just keep in mind that a symbol notated with a leading colon is in effect a constant that evaluates to itself.
- ,
- Commas are used within the backquote syntax.
- `
- Grave accent (``backquote'') signals that the next expression is a template that may contain commas. The backquote syntax represents a program that will construct a data structure according to the template.
- #
- The number sign signals the beginning of a complicated syntactic structure. The next character designates the precise syntax to follow. For example, #o105 means (105 in octal notation); #x105 means (105 in hexadecimal notation); #b1011 means (1011 in binary notation); #\L denotes a character object for the character L; and #(a b c) denotes a vector of three elements a, b, and c. A particularly important case is that #'fn means (function fn), in a manner analogous to 'form meaning (quote form).
- |
- Vertical bars are used in pairs to surround the name (or part of the name) of a symbol that has many special characters in it. It is roughly equivalent to putting a backslash in front of every character so surrounded. For example, |A(B)|, A|(|B|)|, and A\(B\) all mean the symbol whose name consists of the four characters A, (, B, and ).
- title
- Common Lisp the Language, 2nd Edition
- by Guy L. Steele Jr.
- reference
- data types
- Numbers
- integer data type:
- any integer, positive or negative, has in principle a representation as a Common Lisp data object, subject only to total memory limitations (rather than machine word width).
- rational data type
- the quotient of two integers, if not an integer, is a ratio.
- Floating-point
- numbers of various ranges and precisions are also provided
- Cartesian complex numbers.
- Characters
- represent printed glyphs such as letters or text formatting operations.
- + - * / @ $ % ^ & _ = < > ~ .
- In addition to letters and numbers, the following characters are normally considered to be alphabetic for the purposes of notating symbols:
- ? ! [ ] { }
- These characters are also alphabetic by default but are explicitly reserved to the user for definition as reader macro characters (see section 22.1.3) or any other desired purpose and therefore should not be used routinely in names of symbols:
- Strings
- are one-dimensional arrays of characters.
- Symbols
- unquoted sequences of characters w/o special chars
- each symbol has a property list, or plist.
- even-numbered components (calling the first component zero) are symbols, here functioning as property names,
- odd-numbered components are associated property values.
- Functions are provided for manipulating this property list; in effect, these allow a symbol to be treated as an extensible record structure
- ('atomic symbols') are named data objects.
- Lisp provides machinery for locating a symbol object, given its name (in the form of a string).
- Symbols have property lists,
- which in effect allow symbols to be treated as record structures with an extensible set of named components, each of which may be any Lisp object.
- Symbols name functions and variables within programs.
- Lists
- linked list of cells of type cons.
- a special object (the symbol nil) that is the empty list.
- All other lists are built recursively by adding a new element to the front of an existing list.
- a cons has two components: the 'car' and the 'cdr'.
- The car may hold anything,
- the cdr is made to point to a previously existing list.
- (Conses may actually be used completely generally as two-element record structures, but their most important use is to represent lists.)
- advanced
- Arrays are dimensioned collections of objects. An array can have any non-negative number of dimensions and is indexed by a sequence of integers. A general array can have any Lisp object as a component; other types of arrays are specialized for efficiency and can hold only certain types of Lisp objects. It is possible for two arrays, possibly with differing dimension information, to share the same set of elements (such that modifying one array modifies the other also) by causing one to be displaced to the other. One-dimensional arrays of any kind are called vectors. One-dimensional arrays of characters are called strings. One-dimensional arrays of bits (that is, of integers whose values are 0 or 1) are called bit-vectors.
- Hash tables provide an efficient way of mapping any Lisp object (a key) to an associated object.
- Readtables are used to control the built-in expression parser read.
- Packages are collections of symbols that serve as name spaces. The parser recognizes symbols by looking up character sequences in the current package.
- Pathnames represent names of files in a fairly implementation-independent manner. They are used to interface to the external file system.
- Streams represent sources or sinks of data, typically characters or bytes. They are used to perform I/O, as well as for internal purposes such as parsing strings.
- Random-states are data structures used to encapsulate the state of the built-in random-number generator.
- Structures are user-defined record structures, objects that have named components. The defstruct facility is used to define new structure types. Some Common Lisp implementations may choose to implement certain system-supplied data types, such as bignums, readtables, streams, hash tables, and pathnames, as structures, but this fact will be invisible to the user.
- Functions are objects that can be invoked as procedures; these may take arguments and return values. (All Lisp procedures can be construed to return values and therefore every procedure is a function.) Such objects include compiled-functions (compiled code objects). Some functions are represented as a list whose car is a particular symbol such as lambda. Symbols may also be used as functions.
- program forms
- Defining Named Functions
- defun
- ( defun name lambda-list [[ {declaration}* | doc-string ]] {form}* )
- example
- (defun discriminant (a b c) (declare (number a b c)) "Compute the discriminant for a quadratic equation. Given a, b, and c, the value b^2-4*a*c is calculated. The quadratic equation a*x^2+b*x+c=0 has real, multiple, or complex roots depending on whether this calculated value is positive, zero, or negative, respectively." (- (* b b) (* 4 a c)) )
- name=
- lambda-list =
- declaration=
- doc-string =
- "Compute the discriminant for a quadratic equation. Given a, b, and c, the value b^2-4*a*c is calculated. The quadratic equation a*x^2+b*x+c=0 has real, multiple, or complex roots depending on whether this calculated value is positive, zero, or negative, respectively."
- {form}* =
- advanced
- Control of Time of Evaluation
- Declaring Global Variables and Named Constants
- logical values
- nil
- [Constant]
- The value of nil is always nil. This object represents the logical false value and also the empty list. It can also be written ().
- t
- 6.2. Data Type Predicates
- General Type Predicates
- typep
- [Function]
- (typep obj typ)
- return T iff object obj has type typ
- Specific Data Type Predicates
- null
- [Function]
- null is true if its argument is (), and otherwise is false. This is the same operation performed by the function not; however, not is normally used to invert a Boolean value, whereas null is normally used to test for an empty list. The programmer can therefore express intent by the choice of function name.
- (null x) == (typep x 'null) == (eq x '())
- advanced
- symbolp
- [Function]
- symbolp is true if its argument is a symbol, and otherwise is false.
- (symbolp x) == (typep x 'symbol)
- atom
- [Function]
- The predicate atom is true if its argument is not a cons, and otherwise is false. Note that (atom '()) is true, because ()nil.
- (atom x) == (typep x 'atom) == (not (typep x 'cons))
- listp
- [Function]
- listp is true if its argument is a cons or the empty list (), and otherwise is false. It does not check for whether the list is a ``true list'' (one terminated by nil) or a ``dotted list'' (one terminated by a non-null atom).
- (listp x) == (typep x 'list) == (typep x '(or cons null))
- numberp
- [Function]
- numberp is true if its argument is any kind of number, and otherwise is false.
- (numberp x) == (typep x 'number)
- integerp
- [Function]
- integerp is true if its argument is an integer, and otherwise is false.
- (integerp x) == (typep x 'integer)
- 6.3. Equality Predicates
- eq x y
- (eq x y)
- is true if and only if x and y are the same identical object. (Implementationally, x and y are usually eq if and only if they address the same identical memory location.)
- equal x y
- The equal predicate is true if its arguments are structurally similar (isomorphic) objects.
- A rough rule of thumb is that two objects are equal if and only if their printed representations are the same.
- advanced
- eql
- is the same as eq, except that if the arguments are characters or numbers of the same type then their values are compared. Thus eql tells whether two objects are conceptually the same, whereas eq tells whether two objects are implementationally identical.
- equalp x y
- Two objects are equalp if they are equal; if they are characters and satisfy char-equal, which ignores alphabetic case and certain other attributes of characters; if they are numbers and have the same numerical value, even if they are of different types; or if they have components that are all equalp.
- 6.4. Logical Operators
- not x
- (not x)
- returns t if x is nil, and otherwise returns nil.
- It therefore inverts its argument considered as a Boolean value.
- and {form}*
- (and form1 form2 ... )
- evaluates each form, one at a time, from left to right. If any form evaluates to nil, the value nil is immediately returned without evaluating the remaining forms.
- If every form but the last evaluates to a non-nil value, it returns whatever the last form returns.
- or {form}*
- (or form1 form2 ... )
- evaluates each form, one at a time, from left to right.
- If any form other than the last evaluates to something other than nil, or immediately returns that non-nil value without evaluating the remaining forms.
- If every form but the last evaluates to nil, or returns whatever evaluation of the last of the forms returns. Therefore in general or can be used both for logical operations, where nil stands for false and non-nil values stand for true, and as a conditional expression.
- 7. Control Structure
- 7.1. Constants and Variables
- quote object
- (quote x) simply returns x.
- The object is not evaluated and may be any Lisp object whatsoever.
- allows any Lisp object to be written as a constant value in a program.
- advanced
- function fn
- The value of function is always the functional interpretation of fn; fn is interpreted as if it had appeared in the functional position of a function invocation.
- In particular, if fn is a symbol, the functional definition associated with that symbol is returned; see symbol-function.
- If fn is a lambda-expression, then a ``lexical closure'' is returned, that is, a function that when invoked will execute the body of the lambda-expression in such a way as to observe the rules of lexical scoping properly.
- advanced
- 7.3. Function Invocation
- apply function arg &rest more-args
- This applies function to a list of arguments.
- funcall fn &rest arguments
- (funcall fn a1 a2 ... an) applies the function fn to the arguments a1, a2, ..., an. The fn may not be a special form or a macro; this would not be meaningful.
- 7.4. Simple Sequencing
- progn {form}*
- The progn construct takes a number of forms and evaluates them sequentially, in order, from left to right.
- The values of all the forms but the last are discarded; whatever the last form returns is returned by the progn form.
- One says that all the forms but the last are evaluated for effect, because their execution is useful only for the side effects caused, but the last form is executed for value.
- progn {form}*
- The progn construct takes a number of forms and evaluates them sequentially, in order, from left to right. The values of all the forms but the last are discarded; whatever the last form returns is returned by the progn form. One says that all the forms but the last are evaluated for effect, because their execution is useful only for the side effects caused, but the last form is executed for value.
- advanced
- prog1 first {form}*
- prog1 is similar to progn, but it returns the value of its first form. All the argument forms are executed sequentially; the value of the first form is saved while all the others are executed and is then returned.
- prog2 first second {form}*
- prog2 is similar to prog1, but it returns the value of its second form. All the argument forms are executed sequentially; the value of the second form is saved while all the other forms are executed and is then returned. prog2 is provided mostly for historical compatibility
- 7.5. Establishing New Variable Bindings
- let ({var | (var value)}*) {declaration}* {form}*
- A let form can be used to execute a series of forms with specified variables bound to specified values.
- let* ({var | (var value)}*) {declaration}* {form}*
- let* is similar to let, but the bindings of variables are performed sequentially rather than in parallel. This allows the expression for the value of a variable to refer to variables previously bound in the let* form.
- progv symbols values {form}*
- progv is a special form that allows binding one or more dynamic variables whose names may be determined at run time. The sequence of forms (an implicit progn) is evaluated with the dynamic variables whose names are in the list symbols bound to corresponding values from the list values
- 7.6. Conditionals
- if test then [else]
- The if special form corresponds to the if-then-else construct found in most algebraic programming languages. First the form test is evaluated. If the result is not nil, then the form then is selected; otherwise the form else is selected. Whichever form is selected is then evaluated, and if returns whatever is returned by evaluation of the selected form.
- cond {(test {form}*)}*
- A cond form has a number (possibly zero) of clauses, which are lists of forms. Each clause consists of a test followed by zero or more consequents. For example:
- The first clause whose test evaluates to non-nil is selected; all other clauses are ignored, and the consequents of the selected clause are evaluated in order (as an implicit progn).
- (cond (test-1 consequent-1-1 consequent-1-2 ...) (test-2) (test-3 consequent-3-1 ...) ... )
- (test-1 consequent-1-1 consequent-1-2 ...)
- (test-2)
- (test-3 consequent-3-1 ...)
- case keyform {({({key}*) | key} {form}*)}*
- case is a conditional that chooses one of its clauses to execute by comparing a value to various constants, which are typically keyword symbols, integers, or characters (but may be any objects). Its form is as follows:
- (case keyform (keylist-1 consequent-1-1 consequent-1-2 ...) (keylist-2 consequent-2-1 ...) (keylist-3 consequent-3-1 ...) ...)
- typecase keyform {(type {form}*)}*
- typecase is a conditional that chooses one of its clauses by examining the type of an object. Its form is as follows:
- (typecase keyform (type-1 consequent-1-1 consequent-1-2 ...) (type-2 consequent-2-1 ...) (type-3 consequent-3-1 ...) ...)
- 7.7. Blocks and Exits
- block name {form}*
- The block construct executes each form from left to right, returning whatever is returned by the last form. If, however, a return or return-from form that specifies the same name is executed during the execution of some form, then the results specified by the return or return-from are immediately returned as the value of the block construct, and execution proceeds as if the block had terminated normally. In this, block differs from progn; the progn construct has nothing to do with return.
- return-from name [result]
- return-from is used to return from a block or from such constructs as do and prog that implicitly establish a block. The name is not evaluated and must be a symbol. A block construct with the same name must lexically enclose the occurrence of return-from; whatever the evaluation of result produces is immediately returned from the block. (If the result form is omitted, it defaults to nil. As a matter of style, this form ought to be used to indicate that the particular value returned doesn't matter.)
- return [result]
- (return form) is identical in meaning to (return-from nil form); it returns from a block named nil. Blocks established implicitly by iteration constructs such as do are named nil, so that return will exit properly from such a construct.
- 7.8. Iteration
- 7.8.1. Indefinite Iteration
- loop {form}*
- Each form is evaluated in turn from left to right. When the last form has been evaluated, then the first form is evaluated again, and so on, in a never-ending cycle. The loop construct never returns a value. Its execution must be terminated explicitly, using return or throw, for example.
- 7.8.2. General Iteration
- do
- The do special form provides a generalized iteration facility, with an arbitrary number of ``index variables.'' These variables are bound within the iteration and stepped in parallel in specified ways. They may be used both to generate successive values of interest (such as successive integers) or to accumulate results. When an end condition is met, the iteration terminates with a specified value.
- do ({(var [init [step]])}*) (end-test {result}*) {declaration}* {tag | statement}*
- 7.8.3. Simple Iteration Constructs
- dolist
- dolist (var listform [resultform]) {declaration}* {tag | statement}*
- dolist provides straightforward iteration over the elements of a list. First dolist evaluates the form listform, which should produce a list. It then executes the body once for each element in the list, in order, with the variable var bound to the element. Then resultform (a single form, not an implicit progn) is evaluated, and the result is the value of the dolist form. (When the resultform is evaluated, the control variable var is still bound and has the value nil.) If resultform is omitted, the result is nil.
- An explicit return statement may be used to terminate the loop and return a specified value.
- dotimes
- provides straightforward iteration over a sequence of integers. The expression (dotimes (var countform resultform) . progbody) evaluates the form countform, which should produce an integer. It then performs progbody once for each integer from zero (inclusive) to count (exclusive), in order, with the variable var bound to the integer; if the value of countform is zero or negative, then the progbody is performed zero times. Finally, resultform (a single form, not an implicit progn) is evaluated, and the result is the value of the dotimes form. (When the resultform is evaluated, the control variable var is still bound and has as its value the number of times the body was executed.) If resultform is omitted, the result is nil.
- dotimes (var countform [resultform]) {declaration}* {tag | statement}*
- 7.8.4. Mapping
- mapcar function list &rest more-lists
- mapcar operates on successive elements of the lists.
- First the function is applied to the car of each list, then to the cadr of each list, and so on. (Ideally all the lists are the same length; if not, the iteration terminates when the shortest list runs out, and excess elements in other lists are ignored.)
- The value returned by mapcar is a list of the results of the successive calls to the function.
- maplist function list &rest more-lists
- maplist is like mapcar except that the function is applied to the lists and successive cdr's of those lists rather than to successive elements of the lists.
- mapc function list &rest more-lists
- mapl function list &rest more-lists
- mapcan function list &rest more-lists
- mapcon function list &rest more-lists
- 7.8.5. The ``Program Feature''
- tagbody {tag | statement}*
- The part of a tagbody after the variable list is called the body. An item in the body may be a symbol or an integer, in which case it is called a tag, or an item in the body may be a list, in which case it is called a statement
- prog
- this construct is a synthesis of let, block, and tagbody, allowing bound variables and the use of return and go within a single construct.
- (prog (var1 var2 (var3 init3) var4 (var5 init5)) {declaration}* statement1 tag1 statement2 statement3 statement4 tag2 statement5 ... )
- (go tag)
- special form is used to do a ``go to'' within a tagbody construct.
- The tag must be a symbol or an integer; the tag is not evaluated. go transfers control to the point in the body labelled by a tag eql to the one given.
- If there is no such tag in the body, the bodies of lexically containing tagbody constructs (if any) are examined as well.
- It is an error if there is no matching tag lexically visible to the point of the go.
- 7.9. Structure Traversal and Side Effects
- 7.10. Multiple Values
- Ordinarily the result of calling a Lisp function is a single Lisp object. Sometimes, however, it is convenient for a function to compute several objects and return them. Common Lisp provides a mechanism for handling multiple values directly. This mechanism is cleaner and more efficient than the usual tricks involving returning a list of results or stashing results in global variables.
- 7.10.1. Constructs for Handling Multiple Values
- Normally multiple values are not used. Special forms are required both to produce multiple values and to receive them. If the caller of a function does not request multiple values, but the called function produces multiple values, then the first value is given to the caller and all others are discarded; if the called function produces zero values, then the caller gets nil as a value.
- 7.11. Dynamic Non-Local Exits
- catch tag {form}*
- The catch special form serves as a target for transfer of control by throw. The form tag is evaluated first to produce an object that names the catch; it may be any Lisp object. ...
- throw tag result
- The throw special form transfers control to a matching catch construct. The tag is evaluated first to produce an object called the throw tag; then the result form is evaluated, and its results are saved (if the result form produces multiple values, then all the values are saved). The most recent outstanding catch whose tag matches the throw tag is exited; the saved results are returned as the value(s) of the catch. A catch matches only if the catch tag is eq to the throw tag.
- 7.1.2. Assignment
- The following facilities allow the value of a variable (more specifically, the value associated with the current binding of the variable) to be altered. Such alteration is different from establishing a new binding. Constructs for establishing new bindings of variables are described in section 7.5.
- setq {var form}*
- (setq var1 form1 var2 form2 ...) is the ``simple variable assignment statement'' of Lisp.
- First form1 is evaluated and the result is stored in the variable var1, then form2 is evaluated and the result stored in var2, and so forth.
- setq may be used for assignment of both lexical and special variables.
- set symbol value
- set allows alteration of the value of a dynamic (special) variable. set causes the dynamic variable named by symbol to take on value as its value
- Only the value of the current dynamic binding is altered; if there are no bindings in effect, the most global value is altered.
- advanced
- makunbound symbol
- makunbound causes the dynamic (special) variable named by symbol to become unbound (have no value).
- fmakunbound symbol
- fmakunbound does the analogous thing for the global function definition named by symbol. For example
- cond {(test {form}*)}*
- A cond form has a number (possibly zero) of clauses, which are lists of forms. Each clause consists of a test followed by zero or more consequents. For example:
- The first clause whose test evaluates to non-nil is selected; all other clauses are ignored, and the consequents of the selected clause are evaluated in order (as an implicit progn).
- (cond (test-1 consequent-1-1 consequent-1-2 ...) (test-2) (test-3 consequent-3-1 ...) ... )
- (test-1 consequent-1-1 consequent-1-2 ...)
- (test-2)
- (test-3 consequent-3-1 ...)
- 8. Macros
- Macro Definition
- Macro Expansion
- Destructuring
- Compiler Macros
- Environments
- 9. Declarations
- Declaration Syntax
- Declaration Specifiers
- Type Declaration for Forms
- Links
- 10. Symbols
- A Lisp symbol is a data object that has three user-visible components:
- The print name
- must be a string, which is the sequence of characters used to identify the symbol. Symbols are of great use because a symbol can be located once its name is given (typed, say, on a keyboard). One may ordinarily not alter a symbol's print name.
- The property list
- is a list that effectively provides each symbol with many modifiable named components.
- The package cell
- must refer to a package object. A package is a data structure used to locate a symbol once given the symbol's name. A symbol is uniquely identified by its name only when considered relative to a package. A symbol may appear in many packages, but it can be owned by at most one package. The package cell points to the owner, if any. Package cells are discussed along with packages in chapter 11.
- 10.1. The Property List
- Since its inception, Lisp has associated with each symbol a kind of tabular data structure called a property list (plist for short).
- A property list contains zero or more entries; each entry associates with a key (called the indicator), which is typically a symbol, an arbitrary Lisp object (called the value or, sometimes, the property). There are no duplications among the indicators; a property list may only have one property at a time with a given name. In this way, given a symbol and an indicator (another symbol), an associated value can be retrieved.
- some ops:
- remprop symbol indicator
- This removes from symbol the property with an indicator eq to indicator. The property indicator and the corresponding value are removed by destructively splicing the property list. It returns nil if no such property was found, or non-nil if a property was found.
- symbol-plist symbol
- This returns the list that contains the property pairs of symbol; the contents of the property-list cell are extracted and returned
- getf place indicator &optional default
- getf searches the property list stored in place for an indicator eq to indicator. If one is found, then the corresponding value is returned; otherwise default is returned. If default is not specified, then nil is used for default. Note that there is no way to distinguish an absent property from one whose value is default. Often place is computed from a generalized variable acceptable to setf
- get symbol indicator &optional default
- get searches the property list of symbol for an indicator eq to indicator. The first argument must be a symbol. If one is found, then the corresponding value is returned; otherwise default is returned.
- 10.2. The Print Name
- Every symbol has an associated string called the print name. This string is used as the external representation of the symbol: if the characters in the string are typed in to read (with suitable escape conventions for certain characters), it is interpreted as a reference to that symbol (if it is interned); and if the symbol is printed, print types out the print name. For more information, see the sections on the reader (section 22.1.1) and printer (section 22.1.6).
- symbol-name sym
- This returns the print name of the symbol sym. For example:
- 10.3. Creating Symbols
- An uninterned symbol is a symbol used simply as a data object, with no special cataloguing (it belongs to no particular package). An uninterned symbol is printed as #: followed by its print name. The following are some functions for creating uninterned symbols.
- make-symbol print-name
- (make-symbol print-name) creates a new uninterned symbol, whose print name is the string print-name. The value and function bindings will be unbound and the property list will be empty.
- copy-symbol sym &optional copy-props
- This returns a new uninterned symbol with the same print name as sym.
- gensym &optional x
- gensym invents a print name and creates a new symbol with that print name. It returns the new, uninterned symbol.
- If the argument x is present and is an integer, then x must be non-negative, and the internal counter is set to x for future use; otherwise the internal counter is incremented.
- If x is a string, then that string is made the default prefix for this and future calls to gensym.
- After handling the argument, gensym creates a symbol as it would with no argument.
- keywordp object
- The argument may be any Lisp object. The predicate keywordp is true if the argument is a symbol and that symbol is a keyword (that is, belongs to the keyword package). Keywords are those symbols that are written with a leading colon. Every keyword is a constant, in the sense that it always evaluates to itself.
- 11. Packages
- One problem with earlier Lisp systems is the use of a single name space for all symbols. In large Lisp systems, with modules written by many different programmers, accidental name collisions become a serious problem. Common Lisp addresses this problem through the package system, derived from an earlier package system developed for Lisp Machine Lisp [55]. In addition to preventing name-space conflicts, the package system makes the modular structure of large Lisp systems more explicit.
- 11.6. Built-in Packages
- 12. Numbers
- Common Lisp provides several different representations for numbers. These representations may be divided into four categories: integers, ratios, floating-point numbers, and complex numbers. Many numeric functions will accept any kind of number; they are generic. Other functions accept only certain kinds of numbers.
- 12.3. Comparisons on Numbers
- = all the same
- /= all different
- < monotonically increasing
- > monotonically decreasing
- <= monotonically nondecreasing
- >= monotonically nonincreasing
- max number &rest more-numbers
- The arguments may be any non-complex numbers. max returns the argument that is greatest (closest to positive infinity). min returns the argument that is least (closest to negative infinity).
- min number &rest more-numbers
- The arguments may be any non-complex numbers. max returns the argument that is greatest (closest to positive infinity). min returns the argument that is least (closest to negative infinity).
- 12.4. Arithmetic Operations
- + &rest numbers
- This returns the sum of the arguments. If there are no arguments, the result is 0, which is an identity for this operation.
- - number &rest more-numbers
- The function -, when given one argument, returns the negative of that argument.
- * &rest numbers
- This returns the product of the arguments. If there are no arguments, the result is 1, which is an identity for this operation.
- / number &rest more-numbers
- The function /, when given more than one argument, successively divides the first argument by all the others and returns the result.
- advanced
- 1+ number
- (1+ x) is the same as (+ x 1).
- 1- number
- (1- x) is the same as (- x 1). Note that the short name may be confusing: (1- x) does not mean 1-x; rather, it means x-1.
- incf place [delta]
- value of delta is added to the number in the generalized variable named by place, and the sum is stored back into place and returned.
- The form place may be any form acceptable as a generalized variable to setf.
- If delta is not supplied, then the number in place is changed by 1
- decf place [delta]
- value of delta is subtracted from the number in the generalized variable named by place, and the sum is stored back into place and returned.
- The form place may be any form acceptable as a generalized variable to setf.
- If delta is not supplied, then the number in place is changed by 1
- gcd &rest integers
- This returns the greatest common divisor of all the arguments, which must be integers. The result of gcd is always a non-negative integer. If one argument is given, its absolute value is returned. If no arguments are given, gcd returns 0, which is an identity for this operation. For three or more arguments,
- lcm integer &rest more-integers
- This returns the least common multiple of its arguments, which must be integers. The result of lcm is always a non-negative integer. For two arguments that are not both zero,
- advanced
- 12.2. Predicates on Numbers
- zerop number
- This predicate is true if number is zero (the integer zero, a floating-point zero, or a complex zero), and is false otherwise. Regardless of whether an implementation provides distinct representations for positive and negative floating-point zeros, (zerop -0.0) is always true. It is an error if the argument number is not a number.
- plusp number
- This predicate is true if number is strictly greater than zero, and is false otherwise. It is an error if the argument number is not a non-complex number.
- minusp number
- This predicate is true if number is strictly less than zero, and is false otherwise. Regardless of whether an implementation provides distinct representations for positive and negative floating-point zeros, (minusp -0.0) is always false. (The function float-sign may be used to distinguish a negative zero.) It is an error if the argument number is not a non-complex number.
- oddp integer
- This predicate is true if the argument integer is odd (not divisible by 2), and otherwise is false. It is an error if the argument is not an integer.
- evenp integer
- This predicate is true if the argument integer is even (divisible by 2), and otherwise is false. It is an error if the argument is not an integer.
- 12.5. Irrational and Transcendental Functions
- 12.5.1. Exponential and Logarithmic Functions
- exp number
- Returns e raised to the power number, where e is the base of the natural logarithms.
- log number &optional base
- Returns the logarithm of number in the base base, which defaults to e, the base of the natural logarithms.
- sqrt number
- Returns the principal square root of number. If the number is not complex but is negative, then the result will be a complex number.
- isqrt integer
- Integer square root: the argument must be a non-negative integer, and the result is the greatest integer less than or equal to the exact positive square root of the argument.
- 12.5.2. Trigonometric and Related Functions
- abs number
- Returns the absolute value of the argument. For a non-complex number x,
- sin radians
- cos radians
- tan radians
- pi
- This global variable has as its value the best possible approximation to pi in long floating-point format.
- 12.6. Type Conversions and Component Extractions on Numbers
- float number &optional other
- floor number &optional divisor
- ceiling number &optional divisor
- truncate number &optional divisor
- round number &optional divisor
- mod number divisor
- rem number divisor
- 12.7. Logical Operations on Numbers
- The logical operations in this section require integers as arguments; it is an error to supply a non-integer as an argument. The functions all treat integers as if they were represented in two's-complement notation.
- 12.8. Byte Manipulation Functions
- Several functions are provided for dealing with an arbitrary-width field of contiguous bits appearing anywhere in an integer. Such a contiguous set of bits is called a byte. Here the term byte does not imply some fixed number of bits (such as eight), rather a field of arbitrary and user-specifiable width
- 12.9. Random Numbers
- The Common Lisp facility for generating pseudo-random numbers has been carefully defined to make its use reasonably portable. While two implementations may produce different series of pseudo-random numbers, the distribution of values should be relatively independent of such machine-dependent aspects as word size.
- random number &optional state
- (random n) accepts a positive number n and returns a number of the same kind between zero (inclusive) and n (exclusive). The number n may be an integer or a floating-point number. An approximately uniform choice distribution is used.
- 12.10 Implementation Parameters
- The values of the named constants defined in this section are implementation-dependent. They may be useful for parameterizing code in some situations.
- 13. Characters
- Common Lisp provides a character data type; objects of this type represent printed symbols such as letters.
- In general, characters in Common Lisp are not true objects; eq cannot be counted upon to operate on them reliably. In particular, it is possible that the expression
- 14. Sequences
- The type sequence encompasses both lists and vectors (one-dimensional arrays). While these are different data structures with different structural properties leading to different algorithmic uses, they do have a common property: each contains an ordered set of elements. Note that nil is considered to be a sequence of length zero
- 14.1. Simple Sequence Functions
- elt sequence index
- This returns the element of sequence specified by index, which must be a non-negative integer less than the length of the sequence as returned by length. The first element of a sequence has index 0
- subseq sequence start &optional end
- This returns the subsequence of sequence specified by start and end. subseq always allocates a new sequence for a result; it never shares storage with an old sequence. The result subsequence is always of the same type as the argument sequence.
- copy-seq sequence
- A copy is made of the argument sequence; the result is equalp to the argument but not eq to it
- length sequence
- The number of elements in sequence is returned as a non-negative integer. ...
- reverse sequence
- The result is a new sequence of the same kind as sequence, containing the same elements but in reverse order. The argument is not modified.
- 14.3. Modifying Sequences
- replace sequence1 sequence2 &key :start1 :end1 :start2 :end2
- The sequence sequence1 is destructively modified by copying successive elements into it from sequence2. The elements of sequence2 must be of a type that may be stored into sequence1.
- remove ...
- The result is a sequence of the same kind as the argument sequence that has the same elements except that those in the subsequence delimited by :start and :end and satisfying the test (see above) have been removed. This is a non-destructive operation; the result is a copy of the input sequence, save that some elements are not copied. Elements not removed occur in the same order in the result as they did in the argument.
- remove item sequence &key :from-end :test :test-not
- remove-if predicate sequence &key :from-end
- remove-if-not predicate sequence &key :from-end
- delete ...
- This is the destructive counterpart to remove. The result is a sequence of the same kind as the argument sequence that has the same elements except that those in the subsequence delimited by :start and :end and satisfying the test (see above) have been deleted. This is a destructive operation. The argument sequence may be destroyed and used to construct the result; however, the result may or may not be eq to sequence. Elements not deleted occur in the same order in the result as they did in the argument.
- delete item sequence &key :from-end :test :test-not
- delete-if predicate sequence &key :from-end
- delete-if-not predicate sequence &key :from-end
- ... duplicates
- The elements of sequence are compared pairwise, and if any two match, then the one occurring earlier in the sequence is discarded (but if the :from-end argument is true, then the one later in the sequence is discarded). The result is a sequence of the same kind as the argument sequence with enough elements removed so that no two of the remaining elements match. The order of the elements remaining in the result is the same as the order in which they appear in sequence.
- remove-duplicates sequence &key :from-end :test :test-not
- delete-duplicates sequence &key :from-end :test :test-not
- nsubstitute...
- nsubstitute newitem olditem sequence &key :from-end :test :test-not
- nsubstitute-if newitem test sequence &key :from-end
- nsubstitute-if-not newitem test sequence &key :from-end
- This is the destructive counterpart to substitute. The result is a sequence of the same kind as the argument sequence that has the same elements except that those in the subsequence delimited by :start and :end and satisfying the test (see above) have been replaced by newitem. This is a destructive operation. The argument sequence may be destroyed and used to construct the result; however, the result may or may not be eq to sequence
- 14.4. Searching Sequences for Items
- find...
- If the sequence contains an element satisfying the test, then the leftmost such element is returned; otherwise nil is returned.
- find item sequence &key :from-end :test :test-not :start :end :key
- find-if predicate sequence &key :from-end :start :end :key
- find-if-not predicate sequence &key :from-end :start :end :key
- position...
- If the sequence contains an element satisfying the test, then the index within the sequence of the leftmost such element is returned as a non-negative integer; otherwise nil is returned.
- position item sequence &key :from-end :test :test-not
- position-if predicate sequence &key :from-end
- position-if-not predicate sequence &key :from-end
- count...
- The result is always a non-negative integer, the number of elements in the specified subsequence of sequence satisfying the test.
- count item sequence &key :from-end :test :test-not :start :end :key
- count-if predicate sequence &key :from-end :start :end :key
- count-if-not predicate sequence &key :from-end :start :end :key
- mismatch sequence1 sequence2 &key :from-end :test :test-not :key :start1 :start2 :end1 :end2
- The specified subsequences of sequence1 and sequence2 are compared element-wise. If they are of equal length and match in every element, the result is nil. Otherwise, the result is a non-negative integer. This result is the index within sequence1 of the leftmost position at which the two subsequences fail to match; or, if one subsequence is shorter than and a matching prefix of the other, the result is the index relative to sequence1 beyond the last position
- search sequence1 sequence2 &key :from-end :test :test-not :key :start1 :start2 :end1 :end2
- A search is conducted for a subsequence of sequence2 that element-wise matches sequence1. If there is no such subsequence, the result is nil; if there is, the result is the index into sequence2 of the leftmost element of the leftmost such matching subsequence.
- 14.5. Sorting and Merging
- sort sequence predicate &key :key
- The sequence is destructively sorted according to an order determined by the predicate. The predicate should take two arguments, and return non-nil if and only if the first argument is strictly less than the second (in some appropriate sense). If the first argument is greater than or equal to the second (in the appropriate sense), then the predicate should return nil.
- stable-sort sequence predicate &key :key
- The sequence is destructively sorted according to an order determined by the predicate. The predicate should take two arguments, and return non-nil if and only if the first argument is strictly less than the second (in some appropriate sense). If the first argument is greater than or equal to the second (in the appropriate sense), then the predicate should return nil.
- merge result-type sequence1 sequence2 predicate &key :key
- The sequences sequence1 and sequence2 are destructively merged according to an order determined by the predicate. The result is a sequence of type result-type, which must be a subtype of sequence, as for the function coerce. The predicate should take two arguments and return non-nil if and only if the first argument is strictly less than the second (in some appropriate sense). If the first argument is greater than or equal to the second (in the appropriate sense), then the predicate should return nil.
- 15. Lists
- 15.1. Conses
- car list
- This returns the car of list, which must be a cons or (); that is, list must satisfy the predicate listp. By definition, the car of () is (). If the cons is regarded as the first cons of a list, then car returns the first element of the list.
- (car '(a b c)) => a
- cdr list
- This returns the cdr of list, which must be a cons or (); that is, list must satisfy the predicate listp. By definition, the cdr of () is (). If the cons is regarded as the first cons of a list, then cdr returns the rest of the list, which is a list with all elements but the first of the original list. For example:
- (cdr '(a b c)) => (b c)
- c(a|d)*r
- All of the compositions of up to four car and cdr operations are defined as separate Common Lisp functions. The names of these functions begin with c and end with r, and in between is a sequence of a and d letters corresponding to the composition performed by the function.
- For example:
- (cddadr x) is the same as (cdr (cdr (car (cdr x))))
- cons x y
- cons is the primitive function to create a new cons whose car is x and whose cdr is y.
- For example:
- (cons 'a 'b) => (a . b)
- (cons 'a (cons 'b (cons 'c '()))) => (a b c)
- (cons 'a '(b c d)) => (a b c d)
- tree-equal x y &key :test :test-not
- This is a predicate that is true if x and y are isomorphic trees with identical leaves, that is, if x and y are atoms that satisfy the test (by default eql), or if they are both conses and their car's are tree-equal and their cdr's are tree-equal.
- 15.2. Lists
- endp object
- The predicate endp is the recommended way to test for the end of a list. It is false of conses, true of nil, and an error for all other arguments
- list-length list
- list-length returns, as an integer, the length of list. list-length differs from length when the list is circular; length may fail to return, whereas list-length will return nil.
- nth n list
- (nth n list) returns the nth element of list, where the car of the list is the ``zeroth'' element. The argument n must be a non-negative integer. If the length of the list is not greater than n, then the result is (), that is, nil. (This is consistent with the idea that the car and cdr of () are each ().)
- list &rest args
- list constructs and returns a list of its arguments.
- For example:
- (list 3 4 'a (car '(b . c)) (+ 6 -2)) => (3 4 a b 4)
- append &rest lists
- The arguments to append are lists. The result is a list that is the concatenation of the arguments. The arguments are not destroyed.
- For example:
- (append '(a b c) '(d e f) '() '(g)) => (a b c d e f g)
- 15.5. Using Lists as Sets
- member...
- The list is searched for an element that satisfies the test. If none is found, nil is returned; otherwise, the tail of list beginning with the first element that satisfied the test is returned. The list is searched on the top level only. These functions are suitable for use as predicates.
- member item list &key :test :test-not :key
- member-if predicate list &key :key
- member-if-not predicate list &key :key
- tailp sublist list
- This predicate is true if sublist is a sublist of list (that is, one of the conses that makes up list); otherwise it is false. Another way to look at this is that tailp is true if (nthcdr n list) is sublist, for some value of n.
- adjoin item list &key :test :test-not :key
- adjoin is used to add an element to a set, provided that it is not already a member.
- union...
- union takes two lists and returns a new list containing everything that is an element of either of the lists. If there is a duplication between two lists, only one of the duplicate instances will be in the result. If either of the arguments has duplicate entries within it, the redundant entries may or may not appear in the result.
- union list1 list2 &key :test :test-not :key
- nunion list1 list2 &key :test :test-not :key
- intersection ...
- intersection list1 list2 &key :test :test-not :key
- nintersection list1 list2 &key :test :test-not :key
- intersection takes two lists and returns a new list containing everything that is an element of both argument lists. If either list has duplicate entries, the redundant entries may or may not appear in the result.
- set-difference...
- set-difference returns a list of elements of list1 that do not appear in list2. This operation is not destructive.
- set-difference list1 list2 &key :test :test-not :key
- nset-difference list1 list2 &key :test :test-not :key
- set-exclusive-or ...
- set-exclusive-or returns a list of elements that appear in exactly one of list1 and list2. This operation is not destructive.
- set-exclusive-or list1 list2 &key :test :test-not :key
- nset-exclusive-or list1 list2 &key :test :test-not :key
- subsetp list1 list2 &key :test :test-not :key
- subsetp is a predicate that is true if every element of list1 appears in (``matches'' some element of) list2, and false otherwise
- 15.6. Association Lists
- An association list, or a-list, is a data structure used very frequently in Lisp. An a-list is a list of pairs (conses); each pair is an association. The car of a pair is called the key, and the cdr is called the datum.
- acons key datum a-list
- acons constructs a new association list by adding the pair (key . datum) to the old a-list.
- pairlis keys data &optional a-list
- pairlis takes two lists and makes an association list that associates elements of the first list to corresponding elements of the second list. It is an error if the two lists keys and data are not of the same length. If the optional argument a-list is provided, then the new pairs are added to the front of it.
- assoc...
- Each of these searches the association list a-list. The value is the first pair in the a-list such that the car of the pair satisfies the test, or nil if there is no such pair in the a-list.
- assoc item a-list &key :test :test-not :key
- assoc-if predicate a-list
- assoc-if-not predicate a-list
- rassoc...
- rassoc is the reverse form of assoc; it searches for a pair whose cdr satisfies the test, rather than the car. If the a-list is considered to be a mapping, then rassoc treats the a-list as representing the inverse mapping. For example:
- rassoc-if predicate a-list &key :key
- rassoc-if-not predicate a-list &key :key
- 16. Hash Tables
- A hash table is a Lisp object that can efficiently map a given Lisp object to another Lisp object. Each hash table has a set of entries, each of which associates a particular key with a particular value. The basic functions that deal with hash tables can create entries, delete entries, and find the value that is associated with a given key. Finding the value is very fast, even if there are many entries, because hashing is used; this is an important advantage of hash tables over property lists.
- Hash tables are created with the function make-hash-table, which takes various options, including which kind of hash table to make (the default being the eql kind). To look up a key and find the associated value, use gethash. New entries are added to hash tables using setf with gethash. To remove an entry, use remhash. Here is a simple example.
- (setq a (make-hash-table))
- (setf (gethash 'color a) 'brown)
- (setf (gethash 'name a) 'fred)
- (gethash 'color a) => brown
- (gethash 'name a) => fred
- (gethash 'pointy a) => nil
- 17. Arrays
- An array is an object with components arranged according to a rectilinear coordinate system. In principle, an array in Common Lisp may have any number of dimensions, including zero. (A zero-dimensional array has exactly one element.) In practice, an implementation may limit the number of dimensions supported, but every Common Lisp implementation must support arrays of up to seven dimensions. Each dimension is a non-negative integer; if any dimension of an array is zero, the array has no elements.
- 18. Strings
- A string is a specialized vector (one-dimensional array) whose elements are characters
- 18.1. String Access
- _char
- The given index must be a non-negative integer less than the length of string, which must be a string. The character at position index of the string is returned as a character object. (This character will necessarily satisfy the predicate string-char-p.)
- char string index
- schar simple-string index
- 18.2. String Comparison
- string= string1 string2 &key :start1 :end1 :start2 :end2
- string= compares two strings and is true if they are the same (corresponding characters are identical) but is false if they are not. The function equal calls string= if applied to two strings.
- string-equal string1 string2 &key :start1 :end1 :start2 :end2
- string-equal is just like string= except that differences in case are ignored; two characters are considered to be the same if char-equal is true of them.
- stringx...
- These functions compare the two string arguments lexicographically, and the result is nil unless string1 is respectively less than, greater than, less than or equal to, greater than or equal to, or not equal to string2. If the condition is satisfied, however, then the result is the index within the strings of the first character position at which the strings fail to match; put another way, the result is the length of the longest common prefix of the strings.
- string< string1 string2 &key :start1 :end1 :start2 :end2
- string> string1 string2 &key :start1 :end1 :start2 :end2
- string<= string1 string2 &key :start1 :end1 :start2 :end2
- string>= string1 string2 &key :start1 :end1 :start2 :end2
- string/= string1 string2 &key :start1 :end1 :start2 :end2
- str<compar>...
- These are exactly like string<, string>, string<=, string>=, and string/=, respectively, except that distinctions between uppercase and lowercase letters are ignored. It is as if char-lessp were used instead of char< for comparing characters.
- string-lessp string1 string2 &key :start1 :end1 :start2 :end2
- string-greaterp string1 string2 &key :start1 :end1 :start2 :end2
- string-not-greaterp string1 string2 &key :start1 :end1 :start2 :end2
- string-not-lessp string1 string2 &key :start1 :end1 :start2 :end2
- string-not-equal string1 string2 &key :start1 :end1 :start2 :end2
- 19. Structures
- 19.1. Introduction to Structures
- The structure facility is embodied in the defstruct macro, which allows the user to create and use aggregate data types with named elements. These are like ``structures'' in PL/I, or ``records'' in Pascal.
- 20. The Evaluator
- The mechanism that executes Lisp programs is called the evaluator. More precisely, the evaluator accepts a form and performs the computation specified by the form. This mechanism is made available to the user through the function eval.
- 20.1. Run-Time Evaluation of Forms
- eval form
- The form is evaluated in the current dynamic environment and a null lexical environment. Whatever results from the evaluation is returned from the call to eval.
- 20.2. The Top-Level Loop
- Normally one interacts with Lisp through a ``top-level read-eval-print loop,'' so called because it is the highest level of control and consists of an endless loop that reads an expression, evaluates it, and prints the results. One has an effect on the state of the Lisp system only by invoking actions that have side effects.
- 21. Streams
- Streams are objects that serve as sources or sinks of data. Character streams produce or absorb characters; binary streams produce or absorb integers. The normal action of a Common Lisp system is to read characters from a character input stream, parse the characters as representations of Common Lisp data objects, evaluate each object (as a form) as it is read, and print representations of the results of evaluation to an output character stream
- 22. Input/Output
- 22.2. Input Functions
- 22.2.1. Input from Character Streams
- read &optional input-stream eof-error-p eof-value recursive-p
- read reads in the printed representation of a Lisp object from input-stream, builds a corresponding Lisp object, and returns the object.
- read-line &optional input-stream eof-error-p eof-value recursive-p
- read-line reads in a line of text terminated by a newline. It returns the line as a character string (without the newline character). This function is usually used to get a line of input from the user. A second returned value is a flag that is false if the line was terminated normally, or true if end-of-file terminated the (non-empty) line. If end-of-file is encountered immediately (that is, appears to terminate an empty line), then end-of-file processing is controlled in the usual way by the eof-error-p, eof-value, and recursive-p arguments
- read-char &optional input-stream eof-error-p eof-value recursive-p
- read-char inputs one character from input-stream and returns it as a character object
- read-from-string string &optional eof-error-p eof-value &key :start :end :preserve-whitespace
- The characters of string are given successively to the Lisp reader, and the Lisp object built by the reader is returned. Macro characters and so on will all take effect
- parse-integer string &key :start :end :radix :junk-allowed
- This function examines the substring of string delimited by :start and :end (which default to the beginning and end of the string). It skips over whitespace characters and then attempts to parse an integer. The :radix parameter defaults to 10 and must be an integer between 2 and 36.
- 22.3. Output Functions
- 22.3.1. Output to Character Streams
- write object &key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array
- The printed representation of object is written to the output stream specified by :stream, which defaults to the value of *standard-output*.
- write-to-string object &key :escape :radix :base :circle :pretty :level :length :case :gensym :array
- prin_-to-string
- The object is effectively printed as if by write, prin1, or princ, respectively, and the characters that would be output are made into a string, which is returned.
- princ-to-string object
- prin1-to-string object
- terpri &optional output-stream
- The function terpri outputs a newline to output-stream.
- fresh-line &optional output-stream
- fresh-line is similar to terpri but outputs a newline only if the stream is not already at the start of a line.
- 22.3.3 Formated output to char streams
- format destination control-string &rest arguments
- format is used to produce formatted output. format outputs the characters of control-string, except that a tilde (~) introduces a directive.
- The output is sent to destination. If destination is nil, a string is created that contains the output; this string is returned as the value of the call to format.
- directives
;)
- 22.4. Querying the User
- y-or-n-p &optional format-string &rest arguments
- This predicate is for asking the user a question whose answer is either ``yes'' or ``no.'' It types out a message (if supplied), reads an answer in some implementation-dependent manner (intended to be short and simple, like reading a single character such as Y or N), and is true if the answer was ``yes'' or false if the answer was ``no.''
- 23. File System Interface
- 23.2. Opening and Closing Files
- open filename &key :direction :element-type :if-exists :if-does-not-exist :external-format
- This returns a stream that is connected to the file specified by filename. The filename is the name of the file to be opened; it may be a string, a pathname, or a stream. (
- 23.3. Renaming, Deleting, and Other File Operations
- These functions provide a standard interface to operations provided in some form by most file systems. It may be that some implementations of Common Lisp cannot support them all completely
- 23.4. Loading Files
- To load a file is to read through the file, evaluating each form in it. Programs are typically stored in files containing calls to constructs such as defun, defmacro, and defvar, which define the functions and variables of the program.
- 23.5. Accessing Directories
- The following function is a very simple portable primitive for examining a directory. Most file systems can support much more powerful directory-searching primitives, but no two are alike. It is expected that most implementations of Common Lisp will extend the directory function or provide more powerful primitives.
- 24. Errors
- Errors may be signaled for a variety of reasons. Many built-in Common Lisp functions may signal an error when given incorrect arguments. Other functions, described in this chapter, may be called by user programs for the purpose of signaling an error.
- 25. Miscellaneous Features
- The Compiler
- Compiler Diagnostics
- Compiled Functions
- Compilation Environment
- Similarity of Constants
- Documentation
- Debugging Tools
- Environment Inquiries
- Time Functions
- Other Environment Inquiries
- Identity Function
- Links
- 25.2. Documentation
- documentation symbol doc-type
- This function returns the documentation string of type doc-type for the symbol, or nil if none exists. Both arguments must be symbols. Some kinds of documentation are provided automatically by certain Common Lisp constructs if the user writes an optional documentation string within them:
- 25.3. Debugging Tools
- trace {function-name}*
- Invoking trace with one or more function-names (symbols) causes the functions named to be traced. Henceforth, whenever such a function is invoked, information about the call, the arguments passed, and the eventually returned values, if any, will be printed to the stream that is the value of *trace-output*.
- untrace {function-name}*
- dribble &optional pathname
- (dribble pathname) may rebind *standard-input* and *standard-output*, and may take other appropriate action, so as to send a record of the input/output interaction to a file named by pathname. The primary purpose of this is to create a readable record of an interactive session
- apropos string &optional package
- apropos-list string &optional package
- (apropos string) tries to find all available symbols whose print names contain string as a substring. (A symbol may be supplied for the string, in which case the print name of the symbol is used.) Whenever apropos finds a symbol, it prints out the symbol's name; in addition, information about the function definition and dynamic value of the symbol, if any, is printed. If package is specified and not nil, then only symbols available in that package are examined; otherwise ``all'' packages are searched, as if by do-all-symbols.
- 25.4. Environment Inquiries
- 25.4.1. Time Functions
- get-decoded-time
- The current time is returned in Decoded Time format. Nine values are returned: second, minute, hour, date, month, year, day-of-week, daylight-saving-time-p, and time-zone.
- 28. Common Lisp Object System
- This chapter presents the bulk of the first two chapters of the Common Lisp Object System specification; it is substantially identical to these two specification chapters as previously published elsewhere
- 29. Conditions
- The language defined by the first edition contained an enormous lacuna: although facilities were specified for signaling errors, no means was defined for handling errors.
|