Common Lisp
Encyclopedia
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

, published in ANSI
American National Standards Institute
The American National Standards Institute is a private non-profit organization that oversees the development of voluntary consensus standards for products, services, processes, systems, and personnel in the United States. The organization also coordinates U.S. standards with international...

 standard document ANSI INCITS 226-1994 (R2004), (formerly X3.226-1994 (R1999)). From the ANSI Common Lisp standard the Common Lisp HyperSpec
Common Lisp HyperSpec
The Common Lisp HyperSpec is a hypertext html document which is not the ANSI Common Lisp standard, but is based on it with permission from ANSI and X3. It is copyrighted by LispWorks Ltd...

 has been derived for use with web browsers. Common Lisp was developed to standardize the divergent variants of Lisp (though mainly the MacLisp variants) which predated it, thus it is not an implementation but rather a language specification. Several implementations of the Common Lisp standard are available, including free and open source software
Free and open source software
Free and open-source software or free/libre/open-source software is software that is liberally licensed to grant users the right to use, study, change, and improve its design through the availability of its source code...

 and proprietary products.

Common Lisp is a general-purpose, multi-paradigm programming language
Multi-paradigm programming language
Programming languages can be grouped by the number and types of paradigms supported.-Paradigm summaries:A concise reference for the programming paradigms listed in this article....

. It supports a combination of procedural
Procedural programming
Procedural programming can sometimes be used as a synonym for imperative programming , but can also refer to a programming paradigm, derived from structured programming, based upon the concept of the procedure call...

, functional
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

, and object-oriented programming paradigms. As a dynamic programming language
Dynamic programming language
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all...

, it facilitates evolutionary and incremental software development
Iterative and incremental development
Iterative and Incremental development is at the liver of a cyclic software development process developed in response to the weaknesses of the waterfall model...

, with iterative compilation
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...

 into efficient run-time programs.

It also supports optional type annotation and casting, which can be added as necessary at the later profiling and optimization stages, to permit the compiler to generate more efficient code. For instance, fixnum can hold an unboxed integer in a range supported by the hardware and implementation, permitting more efficient arithmetic than on big integers or arbitrary precision types. Similarly, the compiler can be told on a per-module or per-function basis which type safety level is wanted, using optimize declarations.

Common Lisp includes CLOS, an object system that supports multimethods and method combinations. It is extensible through standard features such as Lisp macros (compile-time code rearrangement accomplished by the program itself) and reader macros (extension of syntax to give special meaning to characters reserved for users for this purpose).

Though Common Lisp is not as popular as some non-Lisp languages, many of its features have made their way into other, more widely used programming languages and systems (see Greenspun's Tenth Rule
Greenspun's Tenth Rule
Greenspun's tenth rule of programming is an aphorism in computer programming and especially programming language circles that states:This expresses the opinion that the perceived flexibility and extensibility designed into the Lisp programming language includes all functionality that is...

).

Syntax

Common Lisp is a dialect of Lisp; it uses S-expression
S-expression
S-expressions or sexps are list-based data structures that represent semi-structured data. An S-expression may be a nested list of smaller S-expressions. S-expressions are probably best known for their use in the Lisp family of programming languages...

s to denote both code and data structure. Function and macro calls are written as lists, with the name of the function first, as in these examples:


(+ 2 2) ; adds 2 and 2, yielding 4.


(defvar *x*) ; Ensures that a variable *x* exists,
; without giving it a value. The asterisks are part of
; the name. The symbol *x* is also hereby endowed with
; the property that subsequent bindings of it are dynamic,
; rather than lexical.
(setf *x* 42.1) ; sets the variable *x* to the floating-point value 42.1


;; Define a function that squares a number:
(defun square (x)
(* x x))


;; Execute the function:
(square 3) ; Returns 9



;; the 'let' construct creates a scope for local variables. Here
;; the variable 'a' is bound to 6 and the variable 'b' is bound
;; to 4. Inside the 'let' is a 'body', where the last computed value is returned.
;; Here the result of adding a and b is returned from the 'let' expression.
;; The variables a and b have lexical scope, unless the symbols have been
;; marked as special variables (for instance by a prior DEFVAR).
(let ((a 6)
(b 4))
(+ a b)) ; returns 10

Scalar types

Number types include integer
Integer
The integers are formed by the natural numbers together with the negatives of the non-zero natural numbers .They are known as Positive and Negative Integers respectively...

s, ratio
Ratio
In mathematics, a ratio is a relationship between two numbers of the same kind , usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two which explicitly indicates how many times the first number contains the second In mathematics, a ratio is...

s, floating-point number
Floating point
In computing, floating point describes a method of representing real numbers in a way that can support a wide range of values. Numbers are, in general, represented approximately to a fixed number of significant digits and scaled using an exponent. The base for the scaling is normally 2, 10 or 16...

s, and complex number
Complex number
A complex number is a number consisting of a real part and an imaginary part. Complex numbers extend the idea of the one-dimensional number line to the two-dimensional complex plane by using the number line for the real part and adding a vertical axis to plot the imaginary part...

s. Common Lisp uses bignum
Arbitrary-precision arithmetic
In computer science, arbitrary-precision arithmetic indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system. This contrasts with the faster fixed-precision arithmetic found in most ALU hardware, which typically...

s to represent numerical values of arbitrary size and precision. The ratio type represents fractions exactly, a facility not available in many languages. Common Lisp automatically coerces numeric values among these types as appropriate.

The Common Lisp character
Character (computing)
In computer and machine-based telecommunications terminology, a character is a unit of information that roughly corresponds to a grapheme, grapheme-like unit, or symbol, such as in an alphabet or syllabary in the written form of a natural language....

type is not limited to ASCII
ASCII
The American Standard Code for Information Interchange is a character-encoding scheme based on the ordering of the English alphabet. ASCII codes represent text in computers, communications equipment, and other devices that use text...

 characters. Most modern implementations allow Unicode
Unicode
Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems...

 characters.

The symbol type is common to Lisp languages, but largely unknown outside them. A symbol is a unique, named data object with several parts: name, value, function, property list and package. Of these, value cell and function cell are the most important. Symbols in Lisp are often used similarly to identifiers in other languages: to hold value of a variable; however there are many other uses. Normally, when a symbol is evaluated, its value is returned. Some symbols evaluate to themselves, for example all symbols in the keyword package are self-evaluating. Boolean values in Common Lisp are represented by the self-evaluating symbols T and NIL. Common Lisp has namespaces for symbols, called 'packages'.

A number of functions are available for rounding
Rounding
Rounding a numerical value means replacing it by another value that is approximately equal but has a shorter, simpler, or more explicit representation; for example, replacing $23.4476 with $23.45, or the fraction 312/937 with 1/3, or the expression √2 with 1.414.Rounding is often done on purpose to...

 scalar numeric values in various ways. The function round rounds the argument to the nearest integer, with halfway cases rounded to even The functions truncate, floor, and ceiling round towards zero, down, or up respectively. All these functions return the discarded fractional part as a secondary value. For example, (floor -2.5) yields -3, 0.5; (ceiling -2.5) yields -2, -0.5; (round 2.5) yields 2, 0.5; and (round 3.5) yields 4, -0.5.

Data structures

Sequence types in Common Lisp include lists, vectors, bit-vectors, and strings. There are many operations which can work on any sequence type.

As in almost all other Lisp dialects, lists in Common Lisp are composed of conses, sometimes called cons cells or pairs. A cons is a data structure with two slots, called its car and cdr. A list is a linked chain of conses. Each cons's car refers to a member of the list (possibly another list). Each cons's cdr refers to the next cons—except for the last cons, whose cdr refers to the nil value. Conses can also easily be used to implement trees and other complex data structures; though it is usually advised to use structure
or class instances instead. It is also possible to create circular data structures with conses.

Common Lisp supports multidimensional arrays, and can dynamically resize arrays if required. Multidimensional arrays can be used for matrix mathematics. A vector is a one-dimensional array. Arrays can carry any type as members (even mixed types in the same array) or can be specialized to contain a specific type of members, as in a vector of integers. Many implementations can optimize array functions when the array used is type-specialized. Two type-specialized array types are standard: a string is a vector of characters, while a bit-vector is a vector of bit
Bit
A bit is the basic unit of information in computing and telecommunications; it is the amount of information stored by a digital device or other physical system that exists in one of two possible distinct states...

s.

Hash table
Hash table
In computer science, a hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys , to their associated values . Thus, a hash table implements an associative array...

s
store associations between data objects. Any object may be used as key or value. Hash tables, like arrays, are automatically resized as needed.

Packages are collections of symbols, used chiefly to separate the parts of a program into namespaces
Namespace (computer science)
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols . An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces...

. A package may export some symbols, marking them as part of a public interface. Packages can use other packages.

Structures, similar in use to C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 structs and Pascal
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...

 records, represent arbitrary complex data structures with any number and type of fields (called slots). Structures allow single-inheritance.

Classes are similar to structures, but offer more dynamic features and multiple-inheritance. (See CLOS). Classes have been added late to Common Lisp and there is some conceptual overlap with structures. Objects created of classes are called Instances. A special case are Generic Functions. Generic Functions are both functions and instances.

Functions

Common Lisp supports first-class function
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

s. For instance, it is possible to write functions that take other functions as arguments or return functions as well. This makes it possible to describe very general operations.

The Common Lisp library relies heavily on such higher-order functions. For example, the sort function takes a relational operator
Relational operator
In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities...

 as an argument and key function as an optional keyword argument. This can be used not only to sort any type of data, but also to sort data structures according to a key.


;; Sorts the list using the > and < function as the relational operator.
(sort (list 5 2 6 3 1 4) #'>) ; Returns (6 5 4 3 2 1)
(sort (list 5 2 6 3 1 4) #'<) ; Returns (1 2 3 4 5 6)


;; Sorts the list according to the first element of each sub-list.
(sort (list '(9 A) '(3 B) '(4 C)) #'< :key #'first) ; Returns ((3 B) (4 C) (9 A))


The evaluation model for functions is very simple. When the evaluator encounters a form (F A1 A2...) then it is to assume that the symbol named F is one of the following:
  1. A special operator (easily checked against a fixed list)
  2. A macro operator (must have been defined previously)
  3. The name of a function (default), which may either be a symbol, or a sub-form beginning with the symbol lambda.


If F is the name of a function, then the arguments A1, A2, ..., An are evaluated in left-to-right order, and the function is found and invoked with those values supplied as parameters.

Defining functions

The macro defun
Defun
defun is a macro in the Lisp family of programming languages that defines a function in the global environment that uses the form:...

 defines functions where a function definition gives the name of the function, the names of any arguments, and a function body:


(defun square (x)
(* x x))


Function definitions may include declarations, which provide hints to the compiler about optimization settings or the data types of arguments. They may also include documentation strings (docstrings), which the Lisp system may use to provide interactive documentation:


(defun square (x)
"Calculates the square of the single-float x."
(declare (single-float x) (optimize (speed 3) (debug 0) (safety 1)))
(the single-float (* x x)))


Anonymous functions (function literals) are defined using lambda expressions, e.g. (lambda (x) (* x x)) for a function that squares its argument. Lisp programming style frequently uses higher-order functions for which it is useful to provide anonymous functions as arguments.

Local functions can be defined with flet and labels.


(flet ((square (x)
(* x x)))
(square 3))


There are a number of other operators related to the definition and manipulation of functions. For instance, a function may be recompiled with the compile operator. (Some Lisp systems run functions in an interpreter by default unless instructed to compile; others compile every entered function on the fly).

Defining generic functions and methods

The macro defgeneric defines generic functions.
The macro defmethod defines methods. Generic functions are a collection of methods.

Methods can specialize their parameters over classes or objects.

When a generic function is called, multiple-dispatch will determine the correct method to use.


(defgeneric add (a b))



(defmethod add ((a number) (b number))
(+ a b))



(defmethod add ((a vector) (b number))
(map 'vector (lambda (n) (+ n b)) a))



(defmethod add ((a vector) (b vector))
(map 'vector #'+ a b))



(add 2 3) ; returns 5
(add #(1 2 3 4) 7) ; returns #(8 9 10 11)
(add #(1 2 3 4) #(4 3 2 1)) ; returns #(5 5 5 5)


Generic Functions are also a first class data type. There are many more features to Generic Functions and Methods than described above.

The function namespace

The namespace for function names is separate from the namespace for data variables. This is a key difference between Common Lisp and Scheme. For Common Lisp, operators that define names in the function namespace include defun, flet, labels, defmethod and defgeneric.

To pass a function by name as an argument to another function, one must use the function special operator, commonly abbreviated as #'. The first sort example above refers to the function named by the symbol > in the function namespace, with the code #'>. Conversely, to call a function passed in such a way, one would use the funcall operator on the argument.

Scheme's evaluation model is simpler: there is only one namespace, and all positions in the form are evaluated (in any order) -- not just the arguments. Code written in one dialect is therefore sometimes confusing to programmers more experienced in the other. For instance, many Common Lisp programmers like to use descriptive variable names such as list or string which could cause problems in Scheme, as they would locally shadow function names.

Whether a separate namespace for functions is an advantage is a source of contention in the Lisp community. It is usually referred to as the Lisp-1 vs. Lisp-2 debate. Lisp-1 refers to Scheme's model and Lisp-2 refers to Common Lisp's model. These names were coined in a 1988 paper by Richard P. Gabriel and Kent Pitman
Kent Pitman
Kent M. Pitman is the President of and has been involved for many years in the design, implementation and use of Lisp and Scheme systems. He is often better known by his initials KMP.Kent Pitman is the author of the Common Lisp Condition System...

, which extensively compares the two approaches.

Other types

Other data types in Common Lisp include:
  • Pathnames represent files and directories in the filesystem. The Common Lisp pathname facility is more general than most operating systems' file naming conventions, making Lisp programs' access to files broadly portable across diverse systems.
  • Input and output streams represent sources and sinks of binary or textual data, such as the terminal or open files.
  • Common Lisp has a built-in pseudo-random number generator (PRNG). Random state objects represent reusable sources of pseudo-random numbers, allowing the user to seed the PRNG or cause it to replay a sequence.
  • Conditions are a type used to represent errors, exceptions, and other "interesting" events to which a program may respond.
  • Classes are first-class object
    First-class object
    In programming language design, a first-class citizen , in the context of a particular programming language, is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable...

    s, and are themselves instances of classes called class metaobject classes.
  • Readtables are a type of object which control how Common Lisp's reader parses the text of source code. By controlling which readtable is in use when code is read in, the programmer can change or extend the language's syntax.

Scope

Like programs in many other programming languages, Common Lisp programs make use of names to refer to variables, functions, and many other kinds of entities. Named references are subject to scope.

The association between a name and the entity which the name refers to is called a binding.

Scope refers to the set of circumstances in which a name is determined to have a particular binding.

Determiners of scope

The circumstances which determine scope in Common Lisp include:
  • the location of a reference within an expression. If it's the leftmost position of a compound, it refers to a special operator or a macro or function binding, otherwise to a variable binding or something else.
  • the kind of expression in which the reference takes place. For instance, (GO X) means transfer control to label X, whereas (PRINT X) refers to the variable X. Both scopes of X can be active in the same region of program text, since tagbody labels are in a separate namespace from variable names. A special form or macro form has complete control over the meanings of all symbols in its syntax. For instance in (defclass x (a b) ), a class definition, the (a b) is a list of base classes, so these names are looked up in the space of class names, and x isn't a reference to an existing binding, but the name of a new class being derived from a and b. These facts emerge purely from the semantics of defclass. The only generic fact about this expression is that defclass refers to a macro binding; everything else is up to defclass.
  • the location of the reference within the program text. For instance, if a reference to variable X is enclosed in a binding construct such as a LET which defines a binding for X, then the reference is in the scope created by that binding.
  • for a variable reference, whether or not a variable symbol has been, locally or globally, declared special. This determines whether the reference is resolved within a lexical environment, or within a dynamic environment.
  • the specific instance of the environment in which the reference is resolved. An environment is a run-time dictionary which maps symbols to bindings. Each kind of reference uses its own kind of environment. References to lexical variables are resolved in a lexical environment, et cetera. More than one environment can be associated with the same reference. For instance, thanks to recursion or the use of multiple threads, multiple activations of the same function can exist at the same time. These activations share the same program text, but each has its own lexical environment instance.


To understand what a symbol refers to, the Common Lisp programmer must know what kind of reference is being expressed, what kind of scope it uses if it is a variable reference (dynamic versus lexical scope), and also the run-time situation: in what environment is the reference resolved, where was the binding introduced into the environment, et cetera.

Global

Some environments in Lisp are globally pervasive. For instance, if a new type is defined, it is known everywhere thereafter. References to that type look it up in this global environment.

Dynamic

One type of environment in Common Lisp is the dynamic environment. Bindings established in this environment have dynamic extent, which means that a binding is established at the start of the execution of some construct, such as a LET block, and disappears when that construct finishes executing: its lifetime is tied to the dynamic activation and deactivation of a block. However, a dynamic binding is not just visible within that block; it is also visible to all functions invoked from that block. This type of visibility is known as indefinite scope. Bindings which exhibit dynamic extent (lifetime tied to the activation and deactivation of a block) and indefinite scope (visible to all functions which are called from that block) are said to have dynamic scope.

Common Lisp has support for dynamically scoped variables, which are also called special variables. Certain other kinds of bindings are necessarily dynamically scoped also, such as restarts and catch tags. Function bindings cannot be dynamically scoped using FLET (which only provides lexically scoped function bindings), but function objects (a first-level object in Common Lisp) can be assigned to dynamically scoped variables, bound using LET in dynamic scope, then called using FUNCALL or APPLY.

Dynamic scope is extremely useful because it adds referential clarity and discipline to global variable
Global variable
In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms...

s. Global variables are frowned upon in computer science as potential sources of error, because they can give rise to ad-hoc, covert channels of communication among modules that lead to unwanted, surprising interactions.

In Common Lisp, a special variable which has only a top-level binding behaves just like a global variable in other programming languages. A new value can be stored into it, and that value simply replaces what is in the top-level binding. Careless replacement of the value of a global variable is at the heart of bugs caused by use of global variables. However, another way to work with a special variable is to give it a new, local binding within an expression. This is sometimes referred to as "rebinding" the variable. Binding a dynamically scoped variable temporarily creates a new memory location for that variable, and associates the name with that location. While that binding is in effect, all references to that variable refer to the new binding; the previous binding is hidden. When execution of the binding expression terminates, the temporary memory location is gone, and the old binding is revealed, with the original value intact. Of course, multiple dynamic bindings for the same variable can be nested.

In Common Lisp implementations which support multithreading, dynamic scopes are specific to each thread of execution. Thus special variables serve as an abstraction for thread local storage. If one thread rebinds a special variable, this rebinding has no effect on that variable in other threads. The value stored in a binding can only be retrieved by the thread which created that binding. If each thread binds some special variable *X*, then *X* behaves like thread-local storage. Among threads which do not rebind *X*, it behaves like an ordinary global: all of these threads refer to the same top-level binding of *X*.

Dynamic variables can be used to extend the execution context with additional context information which is implicitly passed from function to function without having to appear as an extra function parameter. This is especially useful when the control transfer has to pass through layers of unrelated code, which simply cannot be extended with extra parameters to pass the additional data. A situation like this usually calls for a global variable. That global variable must be saved and restored, so that the scheme doesn't break under recursion: dynamic variable rebinding takes care of this. And that variable must be made thread-local (or else a big mutex must be used) so the scheme doesn't break under threads: dynamic scope implementations can take care of this also.

In the Common Lisp library, there are many standard special variables. For instance, the all standard I/O streams are stored in the top-level bindings of well-known special variables. The standard output stream is stored in *standard-output*.

Suppose a function foo writes to standard output:


(defun foo
(format t "Hello, world"))


To capture its output in a character string, *standard-output* can be bound to a string stream and called:


(with-output-to-string (*standard-output*)
(foo))


-> "Hello, world" ; gathered output returned as a string

Lexical

Common Lisp supports lexical environments. Formally, the bindings in a lexical environment have lexical scope and may have either indefinite extent or dynamic extent, depending on the type of namespace. Lexical scope means that visibility is physically restricted to the block in which the binding is established. References which are not textually (i.e. lexically) embedded in that block simply do not see that binding.

The tags in a TAGBODY have lexical scope. The expression (GO X) is erroneous if it is not actually embedded in a TAGBODY which contains a label X. However, the label bindings disappear when the TAGBODY terminates its execution, because they have dynamic extent. If that block of code is re-entered by the invocation of a lexical closure, it is invalid for the body of that closure to try to transfer control to a tag via GO:


(defvar *stashed*) ;; will hold a function

(tagbody
(setf *stashed* (lambda (go some-label)))
(go end-label) ;; skip the (print "Hello")
some-label
(print "Hello")
end-label)
-> NIL


When the TAGBODY is executed, it first evaluates the setf form which stores a function in the special variable *stashed*. Then the (go end-label) transfers control to end-label, skipping the code (print "Hello"). Since end-label is at the end of the tagbody, the tagbody terminates, yielding NIL. Suppose that the previously remembered function is now called:


(funcall *stashed*) ;; Error!


This situation is erroneous. One implementation's response is an error condition containing the message, "GO: tagbody for tag SOME-LABEL has already been left". The function tried to evaluate (go some-label), which is lexically embedded in the tagbody, and resolves to the label. However, the tagbody isn't executing (its extent has ended), and so the control transfer cannot take place.

Local function bindings in Lisp have lexical scope, and variable bindings also have lexical scope by default. By contrast with GO labels, both of these have indefinite extent. When a lexical function or variable binding is established, that binding continues to exist for as long as references to it are possible, even after the construct which established that binding has terminated. References to a lexical variables and functions after the termination of their establishing construct are possible thanks to lexical closures.

Lexical binding is the default binding mode for Common Lisp variables. For an individual symbol, it can be switched to dynamic scope, either by a local declaration, by a global declaration. The latter may occur implicitly through the use of a construct like DEFVAR or DEFPARAMETER. It is an important convention in Common Lisp programming that special (i.e. dynamically scoped) variables have names which begin and end with an asterisk sigil
Sigil (computer programming)
In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or scope. In 1999 Philip Gwyn adopted the term "to mean the funny character at the front of a Perl variable".- Historical context:...

 * in what is called the “earmuff convention”. If adhered to, this convention effectively creates a separate namespace for special variables, so that variables intended to be lexical are not accidentally made special.

Lexical scope is useful for several reasons.

Firstly, references to variables and functions can be compiled to efficient machine code, because the run-time environment structure is relatively simple. In many cases it can be optimized to stack storage, so opening and closing lexical scopes has minimal overhead. Even in cases where full closures must be generated, access to the closure's environment is still efficient; typically each variable becomes an offset into a vector of bindings, and so a variable reference becomes a simple load or store instruction with a base-plus-offset addressing mode
Addressing mode
Addressing modes are an aspect of the instruction set architecture in most central processing unit designs. The various addressing modes that are defined in a given instruction set architecture define how machine language instructions in that architecture identify the operand of each instruction...

.

Secondly, lexical scope (combined with indefinite extent) gives rise to the lexical closure, which in turn creates a whole paradigm of programming centered around the use of functions being first-class objects, which is at the root of functional programming.

Thirdly, perhaps most importantly, even if lexical closures are not exploited, the use of lexical scope isolates program modules from unwanted interactions. Due to their restricted visibility, lexical variables are private. If one module A binds a lexical variable X, and calls another module B, references to X in B will not accidentally resolve to the X bound in A. B simply has no access to X. For situations in which disciplined interactions through a variable are desirable, Common Lisp provides special variables. Special variables allow for a module A to set up a binding for a variable X which is visible to another module B, called from A. Being able to do this is an advantage, and being able to prevent it from happening is also an advantage; consequently, Common Lisp supports both lexical and dynamic scope.

Macros

A macro in Lisp superficially resembles a function in usage. However, rather than representing an expression which is evaluated, it represents a transformation of the program source code. The macro gets the source it surrounds as arguments, binds them to its parameters and computes a new source form. This new form can also use a macro. The macro expansion is repeated until the new source form does not use a macro. The final computed form is the source code executed at runtime.

Typical uses of macros in Lisp:
  • new control structures (example: looping constructs, branching constructs)
  • scoping and binding constructs
  • simplified syntax for complex and repeated source code
  • top-level defining forms with compile-time side-effects
  • data-driven programming
  • embedded domain specific languages (examples: SQL, HTML, Prolog)


Various standard Common Lisp features also need to be implemented as macros, such as:
  • the standard SETF abstraction, to allow custom compile-time expansions of assignment/access operators
  • WITH-ACCESSORS, WITH-SLOTS, WITH-OPEN-FILE and other similar WITH macros
  • Depending on implementation, IF or COND is a macro built on the other, the special operator; WHEN and UNLESS consist of macros
  • The powerful LOOP domain-specific language


Macros are defined by the defmacro macro. The special operator macrolet allows the definition of local (lexically scoped) macros. It is also possible to define macros for symbols using define-symbol-macro and symbol-macrolet.

Paul Graham's book On Lisp
On Lisp
On Lisp: Advanced Techniques for Common Lisp is a book by Paul Graham on macro programming in Common Lisp. It is currently out of print, but can be freely downloaded as a pdf.-External links:**Free versions of "On Lisp"******...

 describes the use of macros in Common Lisp in detail.

Example using a macro to define a new control structure

Macros allow Lisp programmers to create new syntactic forms in the language. One typical use is to create new control structures. The example macro provides an until looping construct. The syntax is:


(until test form*)


The macro definition for until:

(defmacro until (test &body body)
(let ((start-tag (gensym "START"))
(end-tag (gensym "END")))
`(tagbody ,start-tag
(when ,test (go ,end-tag))
(progn ,@body)
(go ,start-tag)
,end-tag)))


tagbody is a primitive Common Lisp special operator which provides the ability to name tags and use the go form to jump to those tags. The backquote ` provides a notation that provides code templates, where the value of forms preceded with a comma are filled in. Forms preceded with comma and at-sign are spliced in. The tagbody form tests the end condition. If the condition is true, it jumps to the end tag. Otherwise the provided body code is executed and then it jumps to the start tag.

An example form using above until macro:

(until (= (random 10) 0)
(write-line "Hello"))


The code can be expanded using the function macroexpand. The expansion for above example looks like this:

(TAGBODY
#:START1136
(WHEN (ZEROP (RANDOM 10))
(GO #:END1137))
(PROGN (WRITE-LINE "hello"))
(GO #:START1136)
#:END1137)


During macro expansion the value of the variable test is (= (random 10) 0) and the value of the variable body is ((write-line "Hello")). The body is a list of forms.

Symbols are usually automatically upcased. The expansion uses the TAGBODY with two labels. The symbols for these labels are computed by GENSYM and are not interned in any package. Two go forms use these tags to jump to. Since tagbody is a primitive operator in Common Lisp (and not a macro), it will not be expanded into something else. The expanded form uses the when macro, which also will be expanded. Fully expanding a source form is called code walking.

In the fully expanded (walked) form, the when form is replaced by the primitive if:

(TAGBODY
#:START1136
(IF (ZEROP (RANDOM 10))
(PROGN (GO #:END1137))
NIL)
(PROGN (WRITE-LINE "hello"))
(GO #:START1136))
#:END1137)


All macros must be expanded before the source code containing them can be evaluated or compiled normally. Macros can be considered functions that accept and return abstract syntax tree
Abstract syntax tree
In computer science, an abstract syntax tree , or just syntax tree, is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code. The syntax is 'abstract' in the sense that it...

s (Lisp S-expressions). These functions
are invoked before the evaluator or compiler to produce the final source code.
Macros are written in normal Common Lisp, and may use any Common Lisp (or third-party) operator available.

Variable capture and shadowing

Common Lisp macros are capable of what is commonly called variable capture, where symbols in the macro-expansion body coincide with those in the calling context, allowing the programmer to create macros wherein various symbols have special meaning. The term variable capture is somewhat misleading, because all namespaces are vulnerable to unwanted capture, including the operator and function namespace, the tagbody label namespace, catch tag, condition handler and restart namespaces.

Variable capture can introduce software defects. This happens in one of the following two ways:
  • In the first way, a macro expansion can inadvertently make a symbolic reference which the macro writer assumed will resolve in a global namespace, but the code where the macro is expanded happens to provide a local, shadowing definition it which steals that reference. Let this be referred to as type 1 capture.

  • The second way, type 2 capture, is just the opposite: some of the arguments of the macro are pieces of code supplied by the macro caller, and those pieces of code are written such that they make references to surrounding bindings. However, the macro inserts these pieces of code into an expansion which defines its own bindings that accidentally captures some of these references.


The Scheme dialect of Lisp provides a macro-writing system which provides the referential transparency that eliminates both types of capture problem. This type of macro system is sometimes called "hygienic", in particular by its proponents (who regard macro systems which do not automatically solve this problem as unhygienic).

In Common Lisp, macro hygiene is ensured one of two different ways.

One approach is to use gensyms: guaranteed-unique symbols which can be used in a macro-expansion without threat of capture. The use of gensyms in a macro definition is a manual chore, but macros can be written which simplify the instantiation and use of gensyms. Gensyms solve type 2 capture easily, but they are not applicable to type 1 capture in the same way, because the macro expansion cannot rename the interfering symbols in the surrounding code which capture its references. Gensyms could be used to provide stable aliases for the global symbols which the macro expansion needs. The macro expansion would use these secret aliases rather than the well-known names, so redefinition of the well-known names would have no ill effect on the macro.

Another approach is to use packages. A macro defined in its own package can simply use internal symbols in that package in its expansion. The use of packages deals with type 1 and type 2 capture.

However, packages don't solve the type 1 capture of references to standard Common Lisp functions and operators. The reason is that the use of packages to solve capture problems revolves around the use of private symbols (symbols in one package, which are not imported into, or otherwise made visible in other packages). Whereas the Common Lisp library symbols are external, and frequently imported into or made visible in user-defined packages.

The following is an example of unwanted capture in the operator namespace, occurring in the expansion of a macro:


;; expansion of UNTIL makes liberal use of DO
(defmacro until (expression &body body)
`(do ,@body))

;; macrolet establishes lexical operator binding for DO
(macrolet ((do (...) ... something else ...))
(until (= (random 10) 0) (write-line "Hello")))


The UNTIL macro will expand into a form which calls DO which is intended to refer to the standard Common Lisp macro DO. However, in this context, DO may have a completely different meaning, so UNTIL may not work properly.

Common Lisp solves the problem of the shadowing of standard operators and functions by forbidding their redefinition. Because it redefines the standard operator DO, the preceding is actually a fragment of non-conforming Common Lisp, which allows implementations to diagnose and reject it.

Condition system

The condition system is responsible for exception handling
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

 in Common Lisp. It provides conditions, handlers and restarts. Conditions are objects describing an exceptional situation (for example an error). If a condition is signaled, the Common Lisp system searches for a handler for this condition type and calls the handler. The handler can now search for restarts and use one of these restarts to repair the current problem. As part of a user interface (for example of a debugger), these restarts can also be presented to the user, so that the user can select and invoke one of the available restarts. Since the condition handler is called in the context of the error (without unwinding the stack), full error recovery is possible in many cases, where other exception handling systems would have already terminated the current routine. The debugger itself can also be customized or replaced using the *DEBUGGER-HOOK* dynamic variable.

In the following example (using Symbolics Genera) the user tries to open a file in a Lisp function test called from the Read-Eval-Print-LOOP (REPL), when the file does not exist. The Lisp system presents four restarts. The user selects the Retry OPEN using a different pathname restart and enters a different pathname (lispm-init.lisp instead of lispm-int.lisp). The user code does not contain any error handling code. The whole error handling and restart code is provided by the Lisp system, which can handle and repair the error without terminating the user code.


Command: (test ">zippy>lispm-int.lisp")

Error: The file was not found.
For lispm:>zippy>lispm-int.lisp.newest

LMFS:OPEN-LOCAL-LMFS-1
Arg 0: #P"lispm:>zippy>lispm-int.lisp.newest"

s-A, : Retry OPEN of lispm:>zippy>lispm-int.lisp.newest
s-B: Retry OPEN using a different pathname
s-C, : Return to Lisp Top Level in a TELNET server
s-D: Restart process TELNET terminal

-> Retry OPEN using a different pathname
Use what pathname instead [default lispm:>zippy>lispm-int.lisp.newest]:
lispm:>zippy>lispm-init.lisp.newest

...the program continues

Common Lisp Object System (CLOS)

Common Lisp includes a toolkit for object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, the Common Lisp Object System or CLOS, which is one of the most powerful object systems available in any language. For example Peter Norvig
Peter Norvig
Peter Norvig is an American computer scientist. He is currently the Director of Research at Google Inc.-Educational Background:...

 explains how many Design Patterns
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...

 are simpler to implement in a dynamic language with the features of CLOS (Multiple Inheritance, Mixins, Multimethods, Metaclasses, Method combinations, etc.).
Several extensions to Common Lisp for object-oriented programming have been proposed to be included into the ANSI Common Lisp standard, but eventually CLOS was adopted as the standard object-system for Common Lisp. CLOS is a dynamic
Dynamic programming language
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all...

 object system with multiple dispatch
Multiple dispatch
Multiple dispatch or multimethods or function overloading is the feature of some object-oriented programming languages in which a function or method can be dynamically dispatched based on the run time type of more than one of its arguments...

 and multiple inheritance
Multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass....

, and differs radically from the OOP facilities found in static languages such as C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 or Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

. As a dynamic object system, CLOS allows changes at runtime to generic functions and classes. Methods can be added and removed, classes can be added and redefined, objects can be updated for class changes and the class of objects can be changed.

CLOS has been integrated into ANSI Common Lisp. Generic Functions can be used like normal functions and are a first-class data type. Every CLOS class is integrated into the Common Lisp type system. Many Common Lisp types have a corresponding class. There is more potential use of CLOS for Common Lisp. The specification does not say whether conditions are implemented with CLOS. Pathnames and streams could be implemented with CLOS. These further usage possibilities of CLOS for ANSI Common Lisp are not part of the standard. Actual Common Lisp implementations are using CLOS for pathnames, streams, input/output, conditions, the implementation of CLOS itself and more.

Compiler and interpreter

Several implementations of earlier Lisp dialects provided both an interpreter and a compiler. Unfortunately often the semantics were different. These earlier Lisps implemented lexical scoping in the compiler and dynamic scoping in the interpreter. Common Lisp requires that both the interpreter and compiler use lexical scoping by default. The Common Lisp standard describes both the semantics of the interpreter and a compiler. The compiler can be called using the function compile for individual functions and using the function compile-file for files. Common Lisp allows type declarations and provides ways to influence the compiler code generation policy. For the latter various optimization qualities can be given values between 0 (not important) and 3 (most important): speed, space, safety, debug and compilation-speed.

There is also a function to evaluate Lisp code: eval. eval takes code as pre-parsed s-expressions and not, like in some other languages, as text strings. This way code can be constructed with the usual Lisp functions for constructing lists and symbols and then this code can be evaluate with eval. Several Common Lisp implementations (like Clozure CL and SBCL) are implementing eval using their compiler. This way code is compiled, even though it is evaluated using the function eval.

The file compiler is invoked using the function compile-file. The generated file with compiled code is called a fasl (from fast load) file. These fasl files and also source code files can be loaded with the function load into a running Common Lisp system. Depending on the implementation, the file compiler generates byte-code (for example for the Java Virtual Machine
Java Virtual Machine
A Java virtual machine is a virtual machine capable of executing Java bytecode. It is the code execution component of the Java software platform. Sun Microsystems stated that there are over 4.5 billion JVM-enabled devices.-Overview:...

), C language
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 code (which then is compiled with a C compiler) or, directly, native code.

Common Lisp implementations can be used interactively, even though the code gets fully compiled. The idea of an Interpreted language
Interpreted language
Interpreted language is a programming language in which programs are 'indirectly' executed by an interpreter program. This can be contrasted with a compiled language which is converted into machine code and then 'directly' executed by the host CPU...

 thus does not apply for interactive Common Lisp.

The language makes distinction between read-time, compile-time, load-time and run-time, and allows user code to also make this distinction to perform the wanted type of processing at the wanted step.

Some special operators are provided to especially suit interactive development; for instance, DEFVAR will only assign a value to its provided variable if it wasn't already bound, while DEFPARAMETER will always perform the assignment. This distinction is useful when interactively evaluating, compiling and loading code in a live image.

Some features are also provided to help writing compilers and interpreters. Symbols consist of first-level objects and are directly manipulable by user code. The PROGV special operator allows to create lexical bindings programmatically, while packages are also manipulable. The Lisp compiler itself is available at runtime to compile files or individual functions. These make it easy to use Lisp as an intermediate compiler or interpreter for another language.

Birthday paradox

The following program calculates the smallest number of people in a room for whom the probability of completely unique birthdays is less than 50% (the so-called birthday paradox
Birthday paradox
In probability theory, the birthday problem or birthday paradox pertains to the probability that, in a set of n randomly chosen people, some pair of them will have the same birthday. By the pigeonhole principle, the probability reaches 100% when the number of people reaches 366. However, 99%...

, where for 1 person the probability is obviously 100%, for 2 it is 364/365, etc.). (Answer = 23.)


(defconstant +year-size+ 365)

(defun birthday-paradox (probability number-of-people)
(let ((new-probability (* (/ (- +year-size+ number-of-people)
+year-size+)
probability)))
(if (< new-probability 0.5)
(1+ number-of-people)
(birthday-paradox new-probability (1+ number-of-people)))))


Calling the example function using the REPL (Read Eval Print Loop):

CL-USER > (birthday-paradox 1.0 1)
23

Sorting a list of person objects

We define a class PERSON and a method for displaying the name and age of a person.
Next we define a group of persons as a list of PERSON objects.
Then we iterate over the sorted list.


(defclass person
((name :initarg :name :accessor person-name)
(age :initarg :age :accessor person-age))
(:documentation "The class PERSON with slots NAME and AGE."))

(defmethod display ((object person) stream)
"Displaying a PERSON object to an output stream."
(with-slots (name age) object
(format stream "~a (~a)" name age)))

(defparameter *group*
(list (make-instance 'person :name "Bob" :age 33)
(make-instance 'person :name "Chris" :age 16)
(make-instance 'person :name "Ash" :age 23))
"A list of PERSON objects.")

(dolist (person (sort (copy-list *group*)
#'>
:key #'person-age))
(display person *standard-output*)
(terpri))


It prints the three names with descending age.

Bob (33)
Ash (23)
Chris (16)

Exponentiating by squaring

Use of the LOOP macro is demonstrated:


(defun power (x n)
(loop with result = 1
while (plusp n)
when (oddp n) do (setf result (* result x))
do (setf x (* x x)
n (truncate n 2))
finally (return result)))


Example use:


CL-USER > (power 2 200)
1606938044258990275541962092341162602522202993782792835301376


Compare with the built in exponentiation:


CL-USER > (= (expt 2 200) (power 2 200))
T

Find the list of available shells

WITH-OPEN-FILE is a macro that opens a file and provides a stream. When the form is returning, the file is automatically closed. FUNCALL calls a function object. The LOOP collects all lines that match the predicate.


(defun list-matching-lines (file predicate)
"Returns a list of lines in file, for which the predicate applied to
the line returns T."
(with-open-file (stream file)
(loop for line = (read-line stream nil nil)
while line
when (funcall predicate line)
collect it)))


The function AVAILABLE-SHELLS calls above function LIST-MATCHING-LINES with a pathname and an anonymous function as the predicate. The predicate returns the pathname of a shell or NIL (if the string is not the filename of a shell).


(defun available-shells (&optional (file #p"/etc/shells"))
(list-matching-lines
file
(lambda (line)
(and (plusp (length line))
(char= (char line 0) #\/)
(pathname
(string-right-trim '(#\space #\tab) line))))))


An example call using Mac OS X 10.6:


CL-USER > (available-shells)
(#P"/bin/bash" #P"/bin/csh" #P"/bin/ksh" #P"/bin/sh" #P"/bin/tcsh" #P"/bin/zsh")

Comparison with other Lisps

Common Lisp is most frequently compared with, and contrasted to, Scheme—if only because they are the two most popular Lisp dialects. Scheme predates CL, and comes not only from the same Lisp tradition but from some of the same engineers—Guy L. Steele
Guy L. Steele, Jr.
Guy Lewis Steele Jr. , also known as "The Great Quux", and GLS , is an American computer scientist who has played an important role in designing and documenting several computer programming languages.-Biography:...

, with whom Gerald Jay Sussman
Gerald Jay Sussman
Gerald Jay Sussman is the Panasonic Professor of Electrical Engineering at the Massachusetts Institute of Technology . He received his S.B. and Ph.D. degrees in mathematics from MIT in 1968 and 1973 respectively. He has been involved in artificial intelligence research at MIT since 1964...

 designed Scheme, chaired the standards committee for Common Lisp.

Common Lisp is a general-purpose programming language, in contrast to Lisp variants such as Emacs Lisp
Emacs Lisp
Emacs Lisp is a dialect of the Lisp programming language used by the GNU Emacs and XEmacs text editors . It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C...

 and AutoLISP
AutoLISP
AutoLISP is a dialect of Lisp programming language built specifically for use with the full version of AutoCAD and its derivatives, which include AutoCAD Map 3D, AutoCAD Architecture and AutoCAD Mechanical...

 which are embedded extension languages in particular products. Unlike many earlier Lisps, Common Lisp (like Scheme) uses lexical variable scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...

 by default for both interpreted and compiled code.

Most of the Lisp systems whose designs contributed to Common Lisp—such as ZetaLisp and Franz Lisp—used dynamically scoped
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...

 variables in their interpreters and lexically scoped variables in their compilers. Scheme introduced the sole use of lexically scoped variables to Lisp; an inspiration from ALGOL 68
ALGOL 68
ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...

 which was widely recognized as a good idea. CL supports dynamically scoped variables as well, but they must be explicitly declared as "special". There are no differences in scoping between ANSI CL interpreters and compilers.

Common Lisp is sometimes termed a Lisp-2 and Scheme a Lisp-1, referring to CL's use of separate namespaces for functions and variables. (In fact, CL has many namespaces, such as those for go tags, block names, and loop keywords). There is a long-standing controversy between CL and Scheme advocates over the tradeoffs involved in multiple namespaces. In Scheme, it is (broadly) necessary to avoid giving variables names which clash with functions; Scheme functions frequently have arguments named lis, lst, or lyst so as not to conflict with the system function list. However, in CL it is necessary to explicitly refer to the function namespace when passing a function as an argument—which is also a common occurrence, as in the sort example above.

CL also differs from Scheme in its handling of boolean values. Scheme uses the special values #t and #f to represent truth and falsity. CL follows the older Lisp convention of using the symbols T and NIL, with NIL standing also for the empty list. In CL, any non-NIL value is treated as true by conditionals, such as if, whereas in Scheme all non-#f values are treated as true. These conventions allow some operators in both languages to serve both as predicates (answering a boolean-valued question) and as returning a useful value for further computation, but in Scheme the value ' which is equivalent to NIL in Common Lisp evaluates to true in a boolean expression.

Lastly, the Scheme standards documents require tail-call optimization, which the CL standard does not. Most CL implementations do offer tail-call optimization, although often only when the programmer uses an optimization directive. Nonetheless, common CL coding style does not favor the ubiquitous use of recursion that Scheme style prefers—what a Scheme programmer would express with tail recursion, a CL user would usually express with an iterative expression in do, dolist, loop, or (more recently) with the iterate package.

Implementations

See the Category Common Lisp implementations.

Common Lisp is defined by a specification (like Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

 and C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

) rather than by one implementation (like Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 before version 6). There are many implementations, and the standard details areas in which they may validly differ.

In addition, implementations tend to come with library packages, which provide functionality not covered in the standard. Free and open source software
Free and open source software
Free and open-source software or free/libre/open-source software is software that is liberally licensed to grant users the right to use, study, change, and improve its design through the availability of its source code...

 libraries have been created to support such features in a portable way, and are most notably found in the repositories of the Common-Lisp.net and Common Lisp Open Code Collection projects.

Common Lisp implementations may use any mix of native code compilation, byte code compilation or interpretation. Common Lisp has been designed to support incremental compiler
Incremental compiler
The term incremental compiler may refer to two different types of compiler.-Imperative programming:In imperative programming and software development, an incremental compiler is one that when invoked, takes only the changes of a known set of source files and updates any corresponding output files ...

s, file compilers and block compilers. Standard declarations to optimize compilation (such as function inlining or type specialization) are proposed in the language specification. Most Common Lisp implementations compile source code to native machine code
Machine code
Machine code or machine language is a system of impartible instructions executed directly by a computer's central processing unit. Each instruction performs a very specific task, typically either an operation on a unit of data Machine code or machine language is a system of impartible instructions...

. Some implementations can create (optimized) stand-alone applications. Others compile to interpreted bytecode
Bytecode
Bytecode, also known as p-code , is a term which has been used to denote various forms of instruction sets designed for efficient execution by a software interpreter as well as being suitable for further compilation into machine code...

, which is less efficient than native code, but eases binary-code portability. There are also compilers that compile Common Lisp code to C code. The misconception that Lisp is a purely interpreted language is most likely because Lisp environments provide an interactive prompt and that code is compiled one-by-one, in an incremental way. With Common Lisp incremental compilation is widely used.

Some Unix
Unix
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...

-based implementations (CLISP
CLISP
In computing, CLISP is an implementation of the programming language Common Lisp originally developed by Bruno Haible and Michael Stoll for the Atari ST...

, SBCL) can be used as a scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

; that is, invoked by the system transparently in the way that a Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 or Unix shell
Unix shell
A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems...

 interpreter is.

Commercial implementations

Allegro Common Lisp
Allegro Common Lisp
Allegro Common Lisp is a commercial implementation of the Common Lisp programming language developed by Franz Inc. Allegro CL provides the full ANSI Common Lisp standard with many extensions...

: for Microsoft Windows, FreeBSD, Linux, Apple Mac OS X and various UNIX variants. Allegro CL provides an Integrated Development Environment (IDE)
Integrated development environment
An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...

 (for Windows and Linux) and extensive capabilities for application delivery.
Corman Common Lisp
Corman Common Lisp
Corman Common Lisp is a commercial implementation of the Common Lisp programming language featuring support for the Windows operating system.-History:...

: for Microsoft Windows.
Liquid Common Lisp: formerly called Lucid Common Lisp. Only maintenance, no new releases.
LispWorks
LispWorks
LispWorks is a commercial implementation and IDE for the Common Lisp programming language. The software runs on Microsoft Windows, Mac OS X , Linux, FreeBSD, Solaris and HP UX....

: for Microsoft Windows, FreeBSD, Linux, Apple Mac OS X and various UNIX variants. LispWorks provides an Integrated Development Environment (IDE)
Integrated development environment
An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...

 (available for all platforms) and extensive capabilities for application delivery.
Open Genera: for DEC Alpha.
Scieneer Common Lisp
Scieneer Common Lisp
Scieneer Common Lisp is a commercial implementation of the Common Lisp programming language featuring support for Symmetric multiprocessing on a range of Linux, Solaris and HP-UX platforms. The compiler generates fast 64-bit and 32-bit native code.-License:...

: which is designed for high-performance scientific computing.

Freely redistributable implementations

Armed Bear Common Lisp : A CL implementation that runs on the Java Virtual Machine
Java Virtual Machine
A Java virtual machine is a virtual machine capable of executing Java bytecode. It is the code execution component of the Java software platform. Sun Microsystems stated that there are over 4.5 billion JVM-enabled devices.-Overview:...

. It includes a compiler to Java byte code, and allows access to Java libraries from CL. It was formerly just a component of the Armed Bear J Editor.
CLISP
CLISP
In computing, CLISP is an implementation of the programming language Common Lisp originally developed by Bruno Haible and Michael Stoll for the Atari ST...

: A bytecode-compiling implementation, portable and runs on a number of Unix and Unix-like systems (including Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

), as well as Microsoft Windows and several other systems.
Clozure CL
Clozure CL
Clozure CL is a Common Lisp implementation. It implements the full ANSI Common Lisp standard with several extensions...

 (CCL) : Originally a free and open source
Free and open source software
Free and open-source software or free/libre/open-source software is software that is liberally licensed to grant users the right to use, study, change, and improve its design through the availability of its source code...

 fork of Macintosh Common Lisp. As that history implies, CCL was written for the Macintosh, but Clozure CL now runs on Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

, FreeBSD
FreeBSD
FreeBSD is a free Unix-like operating system descended from AT&T UNIX via BSD UNIX. Although for legal reasons FreeBSD cannot be called “UNIX”, as the direct descendant of BSD UNIX , FreeBSD’s internals and system APIs are UNIX-compliant...

, Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

, Solaris and Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

. 32 and 64 bit x86 ports are supported on each platform. Additionally there are Power PC ports for Mac OS and Linux. CCL was previously known as OpenMCL, but that name is no longer used, to avoid confusion with the open source version of Macintosh Common Lisp.
CMUCL
CMUCL
CMUCL is a free Common Lisp implementation, originally developed at Carnegie Mellon University.CMUCL runs on most Unix-like platforms, including Linux and BSD; there is an experimental Windows port as well. Steel Bank Common Lisp is derived from CMUCL...

: Originally from Carnegie Mellon University
Carnegie Mellon University
Carnegie Mellon University is a private research university in Pittsburgh, Pennsylvania, United States....

, now maintained as free and open source software
Free and open source software
Free and open-source software or free/libre/open-source software is software that is liberally licensed to grant users the right to use, study, change, and improve its design through the availability of its source code...

 by a group of volunteers. CMUCL uses a fast native-code compiler. It is available on Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

 and BSD
Berkeley Software Distribution
Berkeley Software Distribution is a Unix operating system derivative developed and distributed by the Computer Systems Research Group of the University of California, Berkeley, from 1977 to 1995...

 for Intel x86; Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

 for Alpha; Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

 for Intel x86 and PowerPC; and Solaris, IRIX, and HP-UX on their native platforms.
Embeddable Common Lisp
Embeddable Common Lisp
Embeddable Common Lisp is a LGPL Common Lisp implementation aimed at producing a small-footprint Lisp system that can be embedded into existing C-based applications...

 (ECL) : ECL includes a bytecode interpreter and compiler. It can also compile Lisp code to machine code via a C compiler. ECL then compiles Lisp code to C, compiles the C code with a C compiler and can then load the resulting machine code. It is also possible to embed ECL in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 programs, and C code into Common Lisp programs.
GNU Common Lisp
GNU Common Lisp
GNU Common Lisp is the GNU Project's Common Lisp compiler, an evolutionary development of Kyoto Common Lisp. It produces native object code by first generating C code and then calling a C compiler....

 (GCL) : The GNU
GNU
GNU is a Unix-like computer operating system developed by the GNU project, ultimately aiming to be a "complete Unix-compatible software system"...

 Project's Lisp compiler. Not yet fully ANSI-compliant, GCL is however the implementation of choice for several large projects including the mathematical tools Maxima, AXIOM
Axiom
In traditional logic, an axiom or postulate is a proposition that is not proven or demonstrated but considered either to be self-evident or to define and delimit the realm of analysis. In other words, an axiom is a logical statement that is assumed to be true...

 and ACL2. GCL runs on Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

 under eleven different architectures, and also under Windows, Solaris, and FreeBSD
FreeBSD
FreeBSD is a free Unix-like operating system descended from AT&T UNIX via BSD UNIX. Although for legal reasons FreeBSD cannot be called “UNIX”, as the direct descendant of BSD UNIX , FreeBSD’s internals and system APIs are UNIX-compliant...

.
Macintosh Common Lisp
Macintosh Common Lisp
Macintosh Common Lisp is an implementation and IDE for the Common Lisp programming language. Various versions of MCL run under Mac OS and Mac OS X....

: Version 5.2 for Apple Macintosh computers with a PowerPC processor running Mac OS X is open source. RMCL (based on MCL 5.2) runs on Intel-based Apple Macintosh computers using the Rosetta binary translator from Apple.
Movitz
Movitz
Movitz is an implementation of the Common Lisp programming language for x86 computers. It runs with no underlying operating system and is intended as "a development platform for operating system kernels, embedded, and single-purpose applications"....

: Implements a Lisp environment for x86 computers without relying on any underlying OS.
Poplog
Poplog
Poplog is a powerful multi-language, multiparadigm, reflective, incrementally compiled software development environment, originally created in the UK for teaching and research in Artificial Intelligence at the University of Sussex.-History:...

: Poplog implements a version of CL, with POP-11
POP-11
POP-11 is a reflective, incrementally compiled programming language with many of the features of an interpreted language. It is the core language of the Poplog programming environment developed originally by the University of Sussex, and recently in the at the...

, and optionally Prolog
Prolog
Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is declarative: the program logic is expressed in terms of...

, and Standard ML
Standard ML
Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML...

 (SML), allowing mixed language programming. For all, the implementation language is POP-11, which is compiled incrementally. It also has an integrated Emacs
Emacs
Emacs is a class of text editors, usually characterized by their extensibility. GNU Emacs has over 1,000 commands. It also allows the user to combine these commands into macros to automate work.Development began in the mid-1970s and continues actively...

-like editor that communicates with the compiler.
Steel Bank Common Lisp
Steel Bank Common Lisp
Steel Bank Common Lisp is a free Common Lisp implementation that features ahigh performance native compiler, Unicode support and threading....

 (SBCL) : A branch from CMUCL
CMUCL
CMUCL is a free Common Lisp implementation, originally developed at Carnegie Mellon University.CMUCL runs on most Unix-like platforms, including Linux and BSD; there is an experimental Windows port as well. Steel Bank Common Lisp is derived from CMUCL...

. "Broadly speaking, SBCL is distinguished from CMU CL by a greater emphasis on maintainability." SBCL runs on the platforms CMUCL does, except HP/UX; in addition, it runs on Linux for AMD64, PowerPC, SPARC, and MIPS, and has experimental support for running on Windows. SBCL does not use an interpreter by default; all expressions are compiled to native code unless the user switches the interpreter on. The SBCL compiler generates fast native code.
Ufasoft Common Lisp: port of CLISP for windows platform with core written in C++.

Other (mostly historical) implementations

Austin Kyoto Common Lisp : an evolution of Kyoto Common Lisp
Butterfly Common Lisp : an implementation written in Scheme for the BBN Butterfly multi-processor computer
CLICC : a Common Lisp to C compiler
CLOE : Common Lisp for PCs by Symbolics
Codemist Common Lisp : used for the commercial version of the computer algebra system Axiom
ExperCommon Lisp : an early implementation for the Apple Macintosh by ExperTelligence
Golden Common Lisp: an implementation for the PC by GoldHill Inc.
Ibuki Common Lisp : a commercialized version of Kyoto Common Lisp
Kyoto Common Lisp
Kyoto Common Lisp
Kyoto Common Lisp is an implementation of Common Lisp by T. Yuasa and M. Hagiya, written in C to run under Unix-like operating systems. KCL is compiled to ANSI C...

: the first Common Lisp compiler that used C as a target language. GCL and ECL originate from this Common Lisp implementation.
L : a small version of Common Lisp for embedded systems
Lucid Common Lisp: a once popular Common Lisp implementation for UNIX systems
Procyon Common Lisp : an implementation for Windows and Mac OS, used by Franz for their Windows port of Allegro CL
Star Sapphire Common LISP : an implementation for the PC
SubL
SubL
SubL is a programming language based on Common Lisp, which can be easily compiled into the C programming language.It is the low-level, efficient language that is used to implement the Cyc inference engine, and knowledge base lookup and matching algorithms....

: a variant of Common Lisp used for the implementation of the Cyc
Cyc
Cyc is an artificial intelligence project that attempts to assemble a comprehensive ontology and knowledge base of everyday common sense knowledge, with the goal of enabling AI applications to perform human-like reasoning....

 knowledge-based system
Top Level Common Lisp : an early implementation for concurrent execution
WCL : a shared library implementation
Vax Common Lisp
Vax Common Lisp
VAX LISP was an implementation of Common Lisp for VMS and ULTRIX on 32-bit VAXs. It was the first Common Lisp to be written for non-Lisp machines. It was initially boot-strapped from Carnegie Mellon University's Spice Lisp by recompiling its output but for VAX machine instruction and to use the...

: Digital Equipment Corporation
Digital Equipment Corporation
Digital Equipment Corporation was a major American company in the computer industry and a leading vendor of computer systems, software and peripherals from the 1960s to the 1990s...

's implementation that ran on VAX
VAX
VAX was an instruction set architecture developed by Digital Equipment Corporation in the mid-1970s. A 32-bit complex instruction set computer ISA, it was designed to extend or replace DEC's various Programmed Data Processor ISAs...

 systems running VMS
OpenVMS
OpenVMS , previously known as VAX-11/VMS, VAX/VMS or VMS, is a computer server operating system that runs on VAX, Alpha and Itanium-based families of computers. Contrary to what its name suggests, OpenVMS is not open source software; however, the source listings are available for purchase...

 or ULTRIX
Ultrix
Ultrix was the brand name of Digital Equipment Corporation's native Unix systems. While ultrix is the Latin word for avenger, the name was chosen solely for its sound.-History:...



Lisp Machine
Lisp machine
Lisp machines were general-purpose computers designed to efficiently run Lisp as their main software language. In a sense, they were the first commercial single-user workstations...

s (from Symbolics
Symbolics
Symbolics refers to two companies: now-defunct computer manufacturer Symbolics, Inc., and a privately held company that acquired the assets of the former company and continues to sell and maintain the Open Genera Lisp system and the Macsyma computer algebra system.The symbolics.com domain was...

, TI and Xerox) provided implementations of Common Lisp in addition to their native Lisp dialect (Lisp Machine Lisp or InterLisp). CLOS was also available. Symbolics provides a version of Common Lisp that is based on ANSI Common Lisp.

Applications

See the Category Common Lisp software.

Common Lisp is used to develop research applications (often in Artificial Intelligence), for rapid development of prototypes or for deployed applications.

Common Lisp is used in many commercial applications, including the Yahoo!
Yahoo!
Yahoo! Inc. is an American multinational internet corporation headquartered in Sunnyvale, California, United States. The company is perhaps best known for its web portal, search engine , Yahoo! Directory, Yahoo! Mail, Yahoo! News, Yahoo! Groups, Yahoo! Answers, advertising, online mapping ,...

 Store web-commerce site, which originally involved Paul Graham and was later rewritten in C++ and Perl. Other notable examples include:
  • ACT-R
    ACT-R
    ACT-R is a cognitive architecture mainly developed by John Robert Anderson at Carnegie Mellon University. Like any cognitive architecture, ACT-R aims to define the basic and irreducible cognitive and perceptual operations that enable the human mind....

    , a cognitive architecture used in a large number of research projects.
  • Authorizer's Assistant, a large rule-based system used by American Express, analyzing credit requests.
  • Cyc
    Cyc
    Cyc is an artificial intelligence project that attempts to assemble a comprehensive ontology and knowledge base of everyday common sense knowledge, with the goal of enabling AI applications to perform human-like reasoning....

    , a long running project with the aim to create a knowledge-based system that provides a huge amount of common sense knowledge
  • The Dynamic Analysis and Replanning Tool
    Dynamic Analysis and Replanning Tool
    The Dynamic Analysis and Replanning Tool, commonly abbreviated to DART, is an artificial intelligence program used by the U.S. military to optimize and schedule the transportation of supplies or personnel and solve other logistical problems....

     (DART), which is said to alone have paid back during the years from 1991 to 1995 for all thirty years of DARPA investments in AI research.
  • G2 from Gensym, a real-time business rules engine (BRE)
  • The development environment for the Jak and Daxter
    Jak and Daxter
    Jak and Daxter is a critically acclaimed video game franchise created by Naughty Dog for the PlayStation 2.The series consists of four main games and two spin-offs,though they are also considered to be part of the main series...

     video game series, developed by Naughty Dog
    Naughty Dog
    Naughty Dog, Inc. is an American video game developer based in Santa Monica, California. Founded by Andy Gavin and Jason Rubin in 1986 as an independent developer, the studio was acquired by Sony Computer Entertainment in 2001...

    .
  • ITA Software
    ITA Software
    ITA Software is a travel industry software company in Cambridge, Massachusetts. The company was founded by computer scientists from the MIT Artificial Intelligence Laboratory in 1996. On July 1, 2010 ITA agreed to be acquired by Google. On April 8th, 2011 the US Department of Justice approved the...

    's low fare search engine, used by travel websites such as Orbitz
    Orbitz
    Orbitz Worldwide, Inc. is an Internet travel company headquartered in the Citigroup Center in Near West Side, Chicago, Illinois. Through its primary web site Orbitz.com, Orbitz Worldwide enables travelers to research, plan and book a broad range of travel products, facilitating 1.5 million flight...

     and Kayak.com
    Kayak.com
    KAYAK is a technology company providing online travel tools through its global family of websites and mobile applications. Started by cofounders of Expedia, Orbitz, and Travelocity, KAYAK allows users to compare information from hundreds of other travel websites in one display when booking travel...

     and airlines such as American Airlines
    American Airlines
    American Airlines, Inc. is the world's fourth-largest airline in passenger miles transported and operating revenues. American Airlines is a subsidiary of the AMR Corporation and is headquartered in Fort Worth, Texas adjacent to its largest hub at Dallas/Fort Worth International Airport...

    , Continental Airlines
    Continental Airlines
    Continental Airlines was a major American airline now merged with United Airlines. On May 3, 2010, Continental Airlines, Inc. and UAL, Inc. announced a merger via a stock swap, and on October 1, 2010, the merger closed and UAL changed its name to United Continental Holdings, Inc...

     and US Airways
    US Airways
    US Airways, Inc. is a major airline based in the U.S. city of Tempe, Arizona. The airline is an operating unit of US Airways Group and is the sixth largest airline by traffic and eighth largest by market value in the country....

    .
  • Mirai, a 3d graphics suite. It was used to animate the face of Gollum in the movie Lord of the Rings: The Two Towers.
  • Prototype Verification System
    Prototype Verification System
    The Prototype Verification System is a specification language integrated with support tools and a theorem prover.It was developed at the Computer Science Laboratory of SRI International in California. PVS is based on a kernel consisting of an extension of Church's theory of types with dependent...

     (PVS), a mechanized environment for formal specification and verification.
  • PWGL is a sophisticated visual programming environment based on Common Lisp, used in Computer assisted composition and sound synthesis.
  • RacerPro, a semantic web reasoning system and information repository.
  • SPIKE, a scheduling system for earth or space based observatories and satellites, notably the Hubble Space Telescope.


There also exist open-source applications written in Common Lisp, such as:
  • ACL2, a full-featured theorem prover for an applicative variant of Common Lisp.
  • Axiom, a sophisticated computer algebra system
    Computer algebra system
    A computer algebra system is a software program that facilitates symbolic mathematics. The core functionality of a CAS is manipulation of mathematical expressions in symbolic form.-Symbolic manipulations:...

    .
  • Maxima, a sophisticated computer algebra system
    Computer algebra system
    A computer algebra system is a software program that facilitates symbolic mathematics. The core functionality of a CAS is manipulation of mathematical expressions in symbolic form.-Symbolic manipulations:...

    .
  • OpenMusic
    OpenMusic
    OpenMusic is an object-oriented visual programming environment for musical composition based on Common Lisp.It may also be used as an all-purpose visual interface to Lisp programming.-History:...

     is an object-oriented visual programming environment based on Common Lisp, used in Computer assisted composition.
  • Stumpwm, a tiling, keyboard driven X11 Window Manager written entirely in Common Lisp.

See also

  • Common Lisp the Language
    Common Lisp the Language
    Common Lisp the Language is an influential book by Guy L. Steele about Common Lisp.-Before standardization:The first edition served as the basis for the ANSI Common Lisp standard. It was written by Guy L. Steele, Jr., Scott Fahlman, Richard P. Gabriel, David A. Moon, and Daniel L...

  • On Lisp
    On Lisp
    On Lisp: Advanced Techniques for Common Lisp is a book by Paul Graham on macro programming in Common Lisp. It is currently out of print, but can be freely downloaded as a pdf.-External links:**Free versions of "On Lisp"******...

  • Practical Common Lisp
    Practical Common Lisp
    Practical Common Lisp is an introductory book on Common Lisp by Peter Seibel which intersperses "practical" chapters along with a fairly complete introduction to the language...


External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK