Common Lisp (CL) is a dialect of the
Lisp programming language
Lisp (historically LISP) is a family of programming languages with a long history and a distinctive, fully parenthesized prefix notation.
Originally specified in 1960, Lisp is the second-oldest high-level programming language still in common u ...
, published in
ANSI
The American National Standards Institute (ANSI ) 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 organi ...
standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The
Common Lisp HyperSpec The Common Lisp HyperSpec is a technical standard document written in the hypertext format ''Hypertext Markup Language'' (HTML). It is not the American National Standards Institute
The American National Standards Institute (ANSI ) is a priv ...
, a
hyperlinked
HTML
The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaSc ...
version, has been derived from the ANSI Common Lisp standard.
The Common Lisp language was developed as a standardized and improved successor of
Maclisp. By the early 1980s several groups were already at work on diverse successors to MacLisp:
Lisp Machine Lisp
Lisp Machine Lisp is a programming language, a dialect of the language Lisp. A direct descendant of Maclisp, it was initially developed in the mid to late 1970s as the system programming language for the Massachusetts Institute of Technology ( ...
(aka ZetaLisp),
Spice Lisp
Spice Lisp (Scientific Personal Integrated Computing Environment) is a programming language, a dialect of Lisp. Its implementation, originally written by Carnegie Mellon University's (CMU) Spice Lisp Group, targeted the microcode of the 16-bit w ...
,
NIL
Nil may refer to:
* nil (the number 0, zero)
Acronyms
* NIL (programming language), an implementation of the Lisp programming language
* Student athlete compensation, Name, Image and Likeness, a set of rules in the American National Collegiate At ...
and
S-1 Lisp S-1 Lisp was a Lisp implementation written in Lisp for the 36-bit pipelined S-1 Mark IIA supercomputer computer architecture, which has 32 megawords of RAM
Ram, ram, or RAM may refer to:
Animals
* A male sheep
* Ram cichlid, a freshwater t ...
. Common Lisp sought to unify, standardise, and extend the features of these MacLisp dialects. Common Lisp is not an implementation, but rather a language
specification
A specification often refers to a set of documented requirements to be satisfied by a material, design, product, or service. A specification is often a type of technical standard.
There are different types of technical or engineering specificati ...
. Several
implementations of the Common Lisp standard are available, including
free and open-source software and proprietary products.
Common Lisp is a general-purpose,
multi-paradigm programming language. It supports a combination of
procedural,
functional, and
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
paradigms. As a
dynamic programming language
In computer science, a dynamic programming language is a class of high-level programming languages, which at runtime execute many common programming behaviours that static programming languages perform during compilation. These behaviors co ...
, it facilitates evolutionary and
incremental software development, with iterative
compilation
Compilation may refer to:
*In computer programming, the translation of source code into object code by a compiler
**Compilation error
**Compilation unit
*Product bundling, a marketing strategy used to sell multiple products
*Compilation thesis
M ...
into efficient run-time programs. This incremental development is often done interactively without interrupting the running application.
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 of safety level is wanted, using ''optimize'' declarations.
Common Lisp includes
CLOS
Clos may refer to:
People
* Clos (surname)
Other uses
* CLOS, Command line-of-sight, a method of guiding a missile to its intended target
* Clos network, a kind of multistage switching network
* Clos (vineyard), a walled vineyard; used in Fran ...
, an
object system
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
that supports
multimethods and method combinations. It is often implemented with a
Metaobject In computer science, a metaobject is an object that manipulates, creates, describes, or implements objects (including itself). The object that the metaobject pertains to is called the base object. Some information that a metaobject might define incl ...
Protocol.
Common Lisp is extensible through standard features such as ''Lisp
macros'' (code transformations) and ''reader macros'' (input parsers for characters).
Common Lisp provides partial backwards compatibility with
Maclisp and John McCarthy's original
Lisp. This allows older Lisp software to be ported to Common Lisp.
History
Work on Common Lisp started in 1981 after an initiative by ARPA manager Bob Engelmore to develop a single community standard Lisp dialect. Much of the initial language design was done via electronic mail. In 1982,
Guy L. Steele Jr.
Guy Lewis Steele Jr. (; born October 2, 1954) is an American computer scientist who has played an important role in designing and documenting several computer programming languages and technical standards.
Biography
Steele was born in Missouri ...
gave the first overview of Common Lisp at the 1982 ACM Symposium on LISP and functional programming.
The first language documentation was published in 1984 as
Common Lisp the Language
''Common Lisp the Language'' is a reference book by Guy L. Steele about a set of technical standards and programming languages named Common Lisp.
History Before standardizing
The first edition (Digital Press, 1984; ; 465 pages) was written by Guy ...
(known as CLtL1), first edition. A second edition (known as CLtL2), published in 1990, incorporated many changes to the language, made during the ANSI Common Lisp standardization process: extended LOOP syntax, the Common Lisp Object System, the Condition System for error handling, an interface to the pretty printer and much more. But CLtL2 does not describe the final ANSI Common Lisp standard and thus is not a documentation of ANSI Common Lisp. The final ANSI Common Lisp standard then was published in 1994. Since then no update to the standard has been published. Various extensions and improvements to Common Lisp (examples are Unicode, Concurrency, CLOS-based IO) have been provided by implementations and libraries.
Syntax
Common Lisp is a dialect of Lisp. It uses
S-expression
In computer programming, an S-expression (or symbolic expression, abbreviated as sexpr or sexp) is an expression in a like-named notation for nested list (tree-structured) data. S-expressions were invented for and popularized by the programming la ...
s to denote both code and data structure. Function calls, macro forms and special forms are written as lists, with the name of the operator first, as in these examples:
(+ 2 2) ; adds 2 and 2, yielding 4. The function's name is '+'. Lisp has no operators as such.
(defvar *x*) ; Ensures that a variable *x* exists,
; without giving it a value. The asterisks are part of
; the name, by convention denoting a special (global) variable.
; 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
Data types
Common Lisp has many
data types.
Scalar types
''Number'' types include
integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the languag ...
s,
ratio
In mathematics, a ratio shows how many times one number contains another. For example, if there are eight oranges and six lemons in a bowl of fruit, then the ratio of oranges to lemons is eight to six (that is, 8:6, which is equivalent to the ...
s,
floating-point number
In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can be r ...
s, and
complex number
In mathematics, a complex number is an element of a number system that extends the real numbers with a specific element denoted , called the imaginary unit and satisfying the equation i^= -1; every complex number can be expressed in the fo ...
s.
Common Lisp uses
bignum
In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, multiple-precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are li ...
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 or Characters may refer to:
Arts, entertainment, and media Literature
* ''Character'' (novel), a 1936 Dutch novel by Ferdinand Bordewijk
* ''Characters'' (Theophrastus), a classical Greek set of character sketches attributed to The ...
'' type is not limited to
ASCII
ASCII ( ), abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices. Because ...
characters. Most modern implementations allow
Unicode
Unicode, formally The Unicode Standard,The formal version reference is is an information technology standard for the consistent encoding, representation, and handling of text expressed in most of the world's writing systems. The standard, wh ...
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 the 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 means replacing a number with an approximate value that has a shorter, simpler, or more explicit representation. For example, replacing $ with $, the fraction 312/937 with 1/3, or the expression with .
Rounding is often done to ob ...
scalar numeric values in various ways. The function
round
rounds the argument to the nearest integer, with halfway cases rounded to the even integer. 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 that 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 or the empty list. 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 in a list, 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 ''adjustable'' 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 bits. Usually, only a few types are supported. 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
The bit is the most basic unit of information in computing and digital communications. The name is a portmanteau of binary digit. The bit represents a logical state with one of two possible values. These values are most commonly represente ...
s.
''
Hash table
In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an ''index'', ...
s'' store associations between data objects. Any object may be used as key or value. Hash tables are automatically resized as needed.
''Packages'' are collections of symbols, used chiefly to separate the parts of a program into
namespaces
In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified.
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 structs and
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
Clos may refer to:
People
* Clos (surname)
Other uses
* CLOS, Command line-of-sight, a method of guiding a missile to its intended target
* Clos network, a kind of multistage switching network
* Clos (vineyard), a walled vineyard; used in Fran ...
). 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 is Generic Functions. Generic Functions are both functions and instances.
Functions
Common Lisp supports
first-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
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
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 (''e.g.'', ) and inequalities (''e.g.'', ).
In pr ...
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 presumes that the symbol named f is one of the following:
# A special operator (easily checked against a fixed list)
# A macro operator (must have been defined previously)
# 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
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 compiler
directives, known as ''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 literal
In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed t ...
s) 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 several other operators related to the definition and manipulation of functions. For instance, a function may be compiled with the
compile
operator. (Some Lisp systems run functions using an interpreter by default unless instructed to compile; others compile every function).
Defining generic functions and methods
The macro
defgeneric
defines
generic function
In computer programming, a generic function is a function defined for polymorphism.
In statically typed languages
In statically typed languages (such as C++ and Java), the term ''generic functions'' refers to a mechanism for ''compile-time pol ...
s. Generic functions are a collection of
methods
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
.
The macro
defmethod
defines methods.
Methods can specialize their parameters over CLOS ''standard classes'', ''system classes'', ''structure classes'' or individual objects. For many types, there are corresponding ''system classes''.
When a generic function is called,
multiple-dispatch will determine the effective 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))
(defmethod add ((a string) (b string))
(concatenate 'string 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)
(add "COMMON " "LISP") ; returns "COMMON LISP"
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 M. Pitman (KMP) is a programmer who has been involved for many years in the design, implementation, and use of systems based on the programming languages Lisp and Scheme. , he has been President of HyperMeta, Inc.
Pitman was chair of the ad h ...
, which extensively compares the two approaches.
Multiple return values
Common Lisp supports the concept of ''multiple values'', where any expression always has a single ''primary value'', but it might also have any number of ''secondary values'', which might be received and inspected by interested callers. This concept is distinct from returning a list value, as the secondary values are fully optional, and passed via a dedicated side channel. This means that callers may remain entirely unaware of the secondary values being there if they have no need for them, and it makes it convenient to use the mechanism for communicating information that is sometimes useful, but not always necessary. For example,
* The
TRUNCATE
function rounds the given number to an
integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the languag ...
towards zero. However, it also returns a remainder as a secondary value, making it very easy to determine what value was truncated. It also supports an optional divisor parameter, which can be used to perform
Euclidean division
In arithmetic, Euclidean division – or division with remainder – is the process of dividing one integer (the dividend) by another (the divisor), in a way that produces an integer quotient and a natural number remainder strictly smaller than ...
trivially:
(let ((x 1266778)
(y 458))
(multiple-value-bind (quotient remainder)
(truncate x y)
(format nil "~A divided by ~A is ~A remainder ~A" x y quotient remainder)))
;;;; => "1266778 divided by 458 is 2765 remainder 408"
*
GETHASH
returns the value of a key in an
associative map
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an a ...
, or the default value otherwise, and a secondary boolean indicating whether the value was found. Thus code which does not care about whether the value was found or provided as the default can simply use it as-is, but when such distinction is important, it might inspect the secondary boolean and react appropriately. Both use cases are supported by the same call and neither is unnecessarily burdened or constrained by the other. Having this feature at the language level removes the need to check for the existence of the key or compare it to
null
Null may refer to:
Science, technology, and mathematics Computing
* Null (SQL) (or NULL), a special marker and keyword in SQL indicating that something has no value
* Null character, the zero-valued ASCII character, also designated by , often use ...
as would be done in other languages.
(defun get-answer (library)
(gethash 'answer library 42))
(defun the-answer-1 (library)
(format nil "The answer is ~A" (get-answer library)))
;;;; Returns "The answer is 42" if ANSWER not present in LIBRARY
(defun the-answer-2 (library)
(multiple-value-bind (answer sure-p)
(get-answer library)
(if (not sure-p)
"I don't know"
(format nil "The answer is ~A" answer))))
;;;; Returns "I don't know" if ANSWER not present in LIBRARY
Multiple values are supported by a handful of standard forms, most common of which are the
MULTIPLE-VALUE-BIND
special form for accessing secondary values and
VALUES
for returning multiple values:
(defun magic-eight-ball ()
"Return an outlook prediction, with the probability as a secondary value"
(values "Outlook good" (random 1.0)))
;;;; => "Outlook good"
;;;; => 0.3187
Other types
Other data types in Common Lisp include:
*''Pathnames'' represent files and directories in the
filesystem
In computing, file system or filesystem (often abbreviated to fs) is a method and data structure that the operating system uses to control how data is Computer data storage, stored and retrieved. Without a file system, data placed in a storage me ...
. 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
A pseudorandom number generator (PRNG), also known as a deterministic random bit generator (DRBG), is an algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers. The PRNG-generate ...
(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
In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include ...
s, and are themselves instances of classes called
metaobject classes (
metaclasses for short).
*''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.
Kinds of environment
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
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the ''global environment'' or ''global s ...
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 the 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, 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
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
and may have either an indefinite extent or dynamic extent, depending on the type of namespace.
Lexical scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
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 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
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
, 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 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
A sigil () is a type of symbol used in magic. The term has usually referred to a pictorial signature of a deity or spirit. In modern usage, especially in the context of chaos magic, sigil refers to a symbolic representation of the practitioner ...
*
in what is called the "
earmuff
Earmuffs are clothing accessories or personal protective equipment designed to cover a person's ears for hearing protection or warmth. They consist of a thermoplastic or metal head-band that fits over the top or back of the head, and a cushion ...
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
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
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 modes are an aspect of the instruction set architecture in most central processing unit (CPU) designs. The various addressing modes that are defined in a given instruction set architecture define how the machine language instructions i ...
.
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
In computer programming, data-driven programming is a programming paradigm in which the program statements describe the data to be matched and the processing required rather than defining a sequence of steps to be taken. Standard examples of dat ...
* embedded domain specific languages (examples:
SQL,
HTML
The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaSc ...
,
Prolog
Prolog is a 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 intended primarily ...
)
* implicit finalization forms
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 describes the use of macros in Common Lisp in detail.
Doug Hoyte's book
Let Over Lambda extends the discussion on macros, claiming "Macros are the single greatest advantage that lisp has as a programming language and the single greatest advantage of any programming language." Hoyte provides several examples of iterative development of macros.
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 of using the above ''until'' macro:
(until (= (random 10) 0)
(write-line "Hello"))
The code can be expanded using the function ''macroexpand-1''. The expansion for the 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
S-expression
In computer programming, an S-expression (or symbolic expression, abbreviated as sexpr or sexp) is an expression in a like-named notation for nested list (tree-structured) data. S-expressions were invented for and popularized by the programming la ...
s – similar to
abstract syntax tree
In computer science, an abstract syntax tree (AST), or just syntax tree, is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language. Each node of the tree denotes a construct occurr ...
s, but not limited to those. 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 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 () (,expression) ,@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
In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
in Common Lisp.
It provides ''conditions'', ''handler''s and ''restart''s. ''Condition''s 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 automatically repair the current problem, using information such as the condition type and any relevant information provided as part of the condition object, and call the appropriate restart function.
These restarts, if unhandled by code, can be presented to users (as part of a user interface, that of a debugger for example), 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. Code found within ''unwind-protect'' forms such as finalizers will also be executed as appropriate despite the exception.
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 zippy>lispm-int.lisp.newest">efault 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 (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, the Common Lisp Object System or
CLOS
Clos may refer to:
People
* Clos (surname)
Other uses
* CLOS, Command line-of-sight, a method of guiding a missile to its intended target
* Clos network, a kind of multistage switching network
* Clos (vineyard), a walled vineyard; used in Fran ...
.
Peter Norvig
Peter Norvig (born December 14, 1956) is an American computer scientist and Distinguished Education Fellow at the Stanford Institute for Human-Centered AI. He previously served as a director of research and search quality at Google. Norvig is t ...
explains how many
Design Patterns 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
Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to:
Physics and engineering
* Dynamics (mechanics)
** Aerodynamics, the study of the motion of air
** Analytical dyna ...
object system with
multiple dispatch
Multiple dispatch or multimethods is a feature of some programming languages in which a function or method can be dynamically dispatched based on the run-time (dynamic) type or, in the more general case, some other attribute of more than one of ...
and
multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
, and differs radically from the OOP facilities found in static languages such as
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
or
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
. 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 use CLOS for pathnames, streams, input–output, conditions, the implementation of CLOS itself and more.
Compiler and interpreter
A Lisp interpreter directly executes Lisp source code provided as Lisp objects (lists, symbols, numbers, ...) read from s-expressions. A Lisp compiler generates
bytecode
Bytecode (also called portable code or p-code) is a form of instruction set designed for efficient execution by a software interpreter. Unlike human-readable source code, bytecodes are compact numeric codes, constants, and references (norma ...
or
machine code
In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a ve ...
from Lisp source code. Common Lisp allows both individual Lisp functions to be compiled in memory and the compilation of whole files to externally stored compiled code (''fasl'' files).
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 evaluated with the function
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),
C language
C (''pronounced like the letter c'') is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities o ...
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
In computer science, an interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program. An interprete ...
thus does not apply for interactive Common Lisp.
The language makes a 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 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.
Code examples
Birthday paradox
The following program calculates the smallest number of people in a room for whom the probability of unique birthdays is less than 50% (the
birthday paradox
In probability theory, the birthday problem asks for the probability that, in a set of randomly chosen people, at least two will share a birthday. The birthday paradox is that, counterintuitively, the probability of a shared birthday exceeds 5 ...
, where for 1 person the probability is obviously 100%, for 2 it is 364/365, etc.). The answer is 23.
By convention, constants in Common Lisp are enclosed with + characters.
(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 the 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))))))
Example results (on 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 Steele
Guy Lewis Steele Jr. (; born October 2, 1954) is an American computer scientist who has played an important role in designing and documenting several computer programming languages and technical standards.
Biography
Steele was born in Missouri ...
, with whom
Gerald Jay Sussman
Gerald Jay Sussman (born February 8, 1947) is the Panasonic Professor of Electrical Engineering at the Massachusetts Institute of Technology (MIT). He received his S.B. and Ph.D. degrees in mathematics from MIT in 1968 and 1973 respectively. H ...
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 is a dialect of the Lisp programming language used as a scripting language by Emacs (a text editor family most commonly associated with GNU Emacs and XEmacs). It is used for implementing most of the editing functionality built into Em ...
and
AutoLISP
AutoLISP is a dialect of the programming language Lisp built specifically for use with the full version of AutoCAD and its derivatives, which include ''AutoCAD Map 3D'', ''AutoCAD Architecture'' and ''AutoCAD Mechanical''. Neither the application ...
which are
extension languages embedded in particular products (GNU Emacs and AutoCAD, respectively). Unlike many earlier Lisps, Common Lisp (like
Scheme) uses lexical variable
scope
Scope or scopes may refer to:
People with the surname
* Jamie Scope (born 1986), English footballer
* John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution
Arts, media, and entertainment
* Cinem ...
by default for both interpreted and compiled code.
Most of the Lisp systems whose designs contributed to Common Lisp—such as
ZetaLisp
Lisp Machine Lisp is a programming language, a dialect of the language Lisp. A direct descendant of Maclisp, it was initially developed in the mid to late 1970s as the system programming language for the Massachusetts Institute of Technology ( ...
and Franz Lisp—used dynamically
scoped 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 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously d ...
. 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
In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion. Tail recu ...
, 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 may refer to:
Places
* Common, a townland in County Tyrone, Northern Ireland
* Boston Common, a central public park in Boston, Massachusetts
* Cambridge Common, common land area in Cambridge, Massachusetts
* Clapham Common, originally com ...
.
Common Lisp is defined by a specification (like
Ada
Ada may refer to:
Places
Africa
* Ada Foah, a town in Ghana
* Ada (Ghana parliament constituency)
* Ada, Osun, a town in Nigeria
Asia
* Ada, Urmia, a village in West Azerbaijan Province, Iran
* Ada, Karaman, a village in Karaman Province, ...
and
C) rather than by one implementation (like
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
). There are many implementations, and the standard details areas in which they may validly differ.
In addition, implementations tend to come with extensions, which provide functionality not covered in the standard:
* Interactive Top-Level (REPL)
* Garbage Collection
* Debugger, Stepper and Inspector
* Weak data structures (hash tables)
* Extensible sequences
* Extensible LOOP
* Environment access
* CLOS Meta-object Protocol
* CLOS based extensible streams
* CLOS based Condition System
* Network streams
* Persistent CLOS
* Unicode support
* Foreign-Language Interface (often to C)
* Operating System interface
* Java Interface
* Threads and Multiprocessing
* Application delivery (applications, dynamic libraries)
* Saving of images
Free and open-source software libraries have been created to support extensions to Common Lisp in a portable way, and are most notably found in the repositories of the Common-Lisp.net and CLOCC (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
An incremental compiler is a kind of incremental computation applied to the field of compilation. Quite naturally, whereas ordinary compilers make a so-called clean build, that is, (re)build all program modules, an incremental compiler recompiles ...
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
In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a ve ...
. Some implementations can create (optimized) stand-alone applications. Others compile to interpreted
bytecode
Bytecode (also called portable code or p-code) is a form of instruction set designed for efficient execution by a software interpreter. Unlike human-readable source code, bytecodes are compact numeric codes, constants, and references (norma ...
, which is less efficient than native code, but eases binary-code portability. Some compilers 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 (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, an ...
-based implementations (
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. Today it supports the Unix and Microsoft Windows operating systems.
CLISP includes an in ...
,
SBCL
Steel Bank Common Lisp (SBCL) is a free Common Lisp implementation that features a high-performance native compiler, Unicode support and threading.
The name "Steel Bank Common Lisp" is a reference to Carnegie Mellon University Common Lisp fro ...
) can be used as a
scripting language
A scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled.
A scripting ...
; that is, invoked by the system transparently in the way that a
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
or
Unix shell
A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating syste ...
interpreter is.
List of implementations
Commercial implementations
;
Allegro Common Lisp
Allegro Common Lisp is a programming language with an integrated development environment (IDE), developed by Franz Inc. It is a dialect of the language Lisp, a commercial software implementation of the language Common Lisp. Allegro CL provides ...
: for Microsoft Windows, FreeBSD, Linux, Apple macOS and various UNIX variants. Allegro CL provides an
Integrated Development Environment (IDE) (for Windows and Linux) and extensive capabilities for application delivery.
;
Liquid Common Lisp: formerly called Lucid Common Lisp. Only maintenance, no new releases.
;
LispWorks
LispWorks is computer software, a proprietary implementation and integrated development environment (IDE) for the programming language Common Lisp. LispWorks was developed by the UK software company Harlequin Ltd., and first published in 1989. Ha ...
: for Microsoft Windows, FreeBSD, Linux, Apple macOS, iOS, Android and various UNIX variants. LispWorks provides an
Integrated Development Environment (IDE) (available for most platforms, but not for iOS and Android) and extensive capabilities for application delivery.
;
mocl: for iOS, Android and macOS.
;
Open Genera
Genera is a commercial operating system and integrated development environment for Lisp machines created by Symbolics. It is essentially a fork of an earlier operating system originating on the Massachusetts Institute of Technology (MIT) AI Lab' ...
: for DEC Alpha.
;
Scieneer Common Lisp: which is designed for high-performance scientific computing.
Freely redistributable implementations
; Armed Bear Common Lisp (ABCL) : A CL implementation that runs on the
Java Virtual Machine. 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.
;
Clasp: A LLVM based implementation that seamlessly interoperates with C++ libraries. Runs on several Unix and Unix-like systems (including
macOS
macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
).
;
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. Today it supports the Unix and Microsoft Windows operating systems.
CLISP includes an in ...
: A bytecode-compiling implementation, portable and runs on several Unix and Unix-like systems (including
macOS
macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
), as well as Microsoft Windows and several other systems.
;
Clozure CL
Clozure CL (CCL) is a Common Lisp implementation. It implements the full ANSI Common Lisp standard with several extensions (CLOS MOP, threads, CLOS conditions, CLOS streams, ...). It contains a command line development environment, an experimenta ...
(CCL) : Originally a
free and open-source fork of Macintosh Common Lisp. As that history implies, CCL was written for the Macintosh, but Clozure CL now runs on
macOS
macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
,
FreeBSD,
Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, w ...
,
Solaris and
Windows
Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for ser ...
. 32 and 64 bit
x86
x86 (also known as 80x86 or the 8086 family) is a family of complex instruction set computer (CISC) instruction set architectures initially developed by Intel based on the Intel 8086 microprocessor and its 8088 variant. The 8086 was intr ...
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 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 ...
: Originally from
Carnegie Mellon University, now maintained as
free and open-source software by a group of volunteers. CMUCL uses a fast native-code compiler. It is available on
Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, w ...
and
BSD
The Berkeley Software Distribution or Berkeley Standard Distribution (BSD) is a discontinued operating system based on Research Unix, developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berk ...
for Intel x86;
Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, w ...
for Alpha;
macOS
macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
for Intel x86 and PowerPC; and Solaris, IRIX, and HP-UX on their native platforms.
;
Corman Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
: for Microsoft Windows. In January 2015 Corman Lisp has been published under MIT license.
;
Embeddable Common Lisp
Embeddable Common Lisp (ECL) is a small implementation of the ANSI Common Lisp programming language that can be used stand-alone or embedded in extant applications written in C. It creates OS-native executables and libraries (i.e. Executable an ...
(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 programs, and C code into Common Lisp programs.
;
GNU Common Lisp
GNU Common Lisp (GCL) is the GNU Project's ANSI 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 is the implementation of choic ...
(GCL) : The
GNU
GNU () is an extensive collection of free software (383 packages as of January 2022), which can be used as an operating system or can be used in parts with other operating systems. The use of the completed GNU tools led to the family of operat ...
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 and (historically)
ACL2
ACL2 ("A Computational Logic for Applicative Common Lisp") is a software system consisting of a programming language, created by Timothy Still it was an extensible theory in a first-order logic, and an automated theorem prover. ACL2 is designed t ...
. GCL runs on
Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, w ...
under eleven different architectures, and also under Windows, Solaris, and
FreeBSD.
;
Macintosh Common Lisp
Macintosh Common Lisp (MCL) is an implementation and IDE for the Common Lisp programming language. Various versions of MCL run under the classic Mac OS (m68k and PPC) and Mac OS X.
Versions of MCL up to and including 5.1 are proprietary. Vers ...
(MCL) : 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.
;
ManKai Common Lisp (MKCL) : A branch of
ECL. MKCL emphasises reliability, stability and overall code quality through a heavily reworked, natively multi-threaded, runtime system. On Linux, MKCL features a fully POSIX compliant runtime system.
; Movitz : Implements a Lisp environment for
x86
x86 (also known as 80x86 or the 8086 family) is a family of complex instruction set computer (CISC) instruction set architectures initially developed by Intel based on the Intel 8086 microprocessor and its 8088 variant. The 8086 was intr ...
computers without relying on any underlying OS.
;
Poplog
Poplog is an open source, reflective, incrementally compiled software development environment for the programming languages POP-11, Common Lisp, Prolog, and Standard ML, originally created in the UK for teaching and research in Artificial I ...
: Poplog implements a version of CL, with
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 recentl ...
, and optionally
Prolog
Prolog is a 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 intended primarily ...
, and
Standard ML (SML), allowing mixed language programming. For all, the implementation language is POP-11, which is compiled incrementally. It also has an integrated
Emacs-like editor that communicates with the compiler.
;
Steel Bank Common Lisp (SBCL) : A branch from
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 ...
. "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, MIPS, Windows x86 and has experimental support for running on Windows AMD64. 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 according to a previous version of
The Computer Language Benchmarks Game
The Computer Language Benchmarks Game (formerly called The Great Computer Language Shootout) is a free software project for comparing how a given subset of simple algorithms can be implemented in various popular programming languages.
The project ...
.
;
Ufasoft Common Lisp: port of CLISP for windows platform with core written in C++.
Other implementations
; Austin Kyoto Common Lisp : an evolution of
Kyoto Common Lisp
Kyoto Common Lisp (KCL) is an implementation of Common Lisp by Taichi Yuasa and Masami Hagiya, written in C to run under Unix-like operating systems. KCL is compiled to ANSI C. It conforms to Common Lisp as described in the 1984 first editio ...
by
Bill Schelter
William Frederick Schelter (1947 – July 30, 2001) was a professor of mathematics at The University of Texas at Austin and a Lisp developer and programmer. Schelter is credited with the development of the GNU Common Lisp (GCL) implementati ...
; Butterfly Common Lisp : an implementation written in Scheme for the
BBN Butterfly The BBN Butterfly was a massively parallel computer built by Bolt, Beranek and Newman in the 1980s. It was named for the "butterfly" multi-stage switching network around which it was built. Each machine had up to 512 CPUs, each with local memory, ...
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 (KCL) is an implementation of Common Lisp by Taichi Yuasa and Masami Hagiya, written in C to run under Unix-like operating systems. KCL is compiled to ANSI C. It conforms to Common Lisp as described in the 1984 first editio ...
: the first Common Lisp compiler that used C as a target language. GCL, ECL and MKCL originate from this Common Lisp implementation.
; L : a small version of Common Lisp for embedded systems developed by IS Robotics, now iRobot
;
Lisp Machine
Lisp machines are general-purpose computers designed to efficiently run Lisp as their main software and programming language, usually via hardware support. They are an example of a high-level language computer architecture, and in a sense, they ...
s (from
Symbolics, 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 an enhanced version Common Lisp.
; 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
Cyc (pronounced ) is a long-term artificial intelligence project that aims to assemble a comprehensive ontology and knowledge base that spans the basic concepts and rules about how the world works. Hoping to capture common sense knowledge, Cyc f ...
: a variant of Common Lisp used for the implementation of the
Cyc
Cyc (pronounced ) is a long-term artificial intelligence project that aims to assemble a comprehensive ontology and knowledge base that spans the basic concepts and rules about how the world works. Hoping to capture common sense knowledge, Cyc f ...
knowledge-based system
; Top Level Common Lisp : an early implementation for concurrent execution
; WCL : a shared library implementation
;
VAX Common Lisp:
Digital Equipment Corporation
Digital Equipment Corporation (DEC ), using the trademark Digital, was a major American company in the computer industry from the 1960s to the 1990s. The company was co-founded by Ken Olsen and Harlan Anderson in 1957. Olsen was president un ...
's implementation that ran on
VAX
VAX (an acronym for Virtual Address eXtension) is a series of computers featuring a 32-bit instruction set architecture (ISA) and virtual memory that was developed and sold by Digital Equipment Corporation (DEC) in the late 20th century. The V ...
systems running
VMS or
ULTRIX
; XLISP : an implementation written by David Betz
Applications
Common Lisp is used to develop research applications (often in
Artificial Intelligence
Artificial intelligence (AI) is intelligence—perceiving, synthesizing, and inferring information—demonstrated by machines, as opposed to intelligence displayed by animals and humans. Example tasks in which this is done include speech r ...
), for rapid development of prototypes or for deployed applications.
Common Lisp is used in many commercial applications, including the
Yahoo!
Yahoo! (, styled yahoo''!'' in its logo) is an American web services provider. It is headquartered in Sunnyvale, California and operated by the namesake company Yahoo Inc., which is 90% owned by investment funds managed by Apollo Global Manage ...
Store web-commerce site, which originally involved
Paul Graham and was later rewritten in
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
and
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
. Other notable examples include:
*
ACT-R
ACT-R (pronounced /ˌækt ˈɑr/; short for "Adaptive Control of Thought—Rational") is a cognitive architecture mainly developed by John Robert Anderson and Christian Lebiere at Carnegie Mellon University. Like any cognitive architecture, ACT-R ...
, 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 (pronounced ) is a long-term artificial intelligence project that aims to assemble a comprehensive ontology and knowledge base that spans the basic concepts and rules about how the world works. Hoping to capture common sense knowledge, Cyc f ...
, a long running project to create a knowledge-based system that provides a huge amount of common sense knowledge.
*
Gensym G2, a real-time expert system and
business rules engine
A business rules engine is a software system that executes one or more business rules in a runtime production environment. The rules might come from legal regulation ("An employee can be fired for any reason or no reason but not for an illegal ...
* Genworks GDL, based on the open-source Gendl kernel.
* The development environment for the ''
Jak and Daxter
''Jak and Daxter'' is an action-adventure video game franchise created by Andy Gavin and Jason Rubin and owned by Sony Interactive Entertainment. The series was originally developed by Naughty Dog with a number of installments being outsourc ...
'' video game series, developed by
Naughty Dog
Naughty Dog, LLC (formerly JAM Software, Inc.) is an American first-party video game developer based in Santa Monica, California. Founded by Andy Gavin and Jason Rubin in 1984, the studio was acquired by Sony Computer Entertainment in 2001. Gav ...
.
*
ITA Software
ITA Software is a travel industry software division of Google, formerly an independent company, in Cambridge, Massachusetts. The company was founded by Jeremy Wertheimer, a computer scientist from the MIT Artificial Intelligence Laboratory and Co ...
's low fare search engine, used by travel websites such as
Orbitz
Orbitz.com is a travel fare aggregator website and travel metasearch engine. The website is owned by Orbitz Worldwide, Inc., a subsidiary of Expedia Group. It is headquartered in the Citigroup Center, Chicago, Illinois.
Background
Origina ...
and
Kayak.com and airlines such as
American Airlines
American Airlines is a major airlines of the United States, major US-based airline headquartered in Fort Worth, Texas, within the Dallas–Fort Worth metroplex. It is the Largest airlines in the world, largest airline in the world when measured ...
,
Continental Airlines and
US Airways
US Airways (formerly USAir) was a major United States airline that operated from 1937 until its merger with American Airlines in 2015. It was originally founded in Pittsburgh as a mail delivery airline called All American Aviation, which soon ...
.
*
Mirai, a 3D graphics suite. It was used to animate the face of
Gollum
Gollum is a fictional character in J. R. R. Tolkien's Middle-earth legendarium. He was introduced in the 1937 fantasy novel '' The Hobbit'', and became important in its sequel, '' The Lord of the Rings''. Gollum was a Stoor Hobbit of the R ...
in the movie ''
Lord of the Rings: The Two Towers''.
* Opusmodus is a music composition system based on Common Lisp, used in
Computer assisted composition.
*
Prototype Verification System
The Prototype Verification System (PVS) is a specification language integrated with support tools and an automated theorem prover, developed at the Computer Science Laboratory of SRI International in Menlo Park, California.
PVS is based on a kern ...
(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.
* Piano, a complete aircraft analysis suite, written in Common Lisp,
used by companies like
Boeing
The Boeing Company () is an American multinational corporation that designs, manufactures, and sells airplanes, rotorcraft, rockets, satellites, telecommunications equipment, and missiles worldwide. The company also provides leasing and p ...
,
Airbus
Airbus SE (; ; ; ) is a European multinational aerospace corporation. Airbus designs, manufactures and sells civil and military aerospace products worldwide and manufactures aircraft throughout the world. The company has three divisions: ' ...
, and
Northrop Grumman
Northrop Grumman Corporation is an American multinational aerospace and defense technology company. With 90,000 employees and an annual revenue in excess of $30 billion, it is one of the world's largest weapons manufacturers and military techn ...
.
*
Grammarly, an English-language writing-enhancement platform, has its core grammar engine written in Common Lisp.
* The
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.
DAR ...
(DART), which is said to alone have paid back during the years from 1991 to 1995 for all thirty years of
DARPA
The Defense Advanced Research Projects Agency (DARPA) is a research and development agency of the United States Department of Defense responsible for the development of emerging technologies for use by the military.
Originally known as the Ad ...
investments in AI research.
*
NASA
The National Aeronautics and Space Administration (NASA ) is an independent agencies of the United States government, independent agency of the US federal government responsible for the civil List of government space agencies, space program ...
's
Jet Propulsion Lab
The Jet Propulsion Laboratory (JPL) is a federally funded research and development center and NASA field center in the City of La Cañada Flintridge, California, United States.
Founded in the 1930s by Caltech researchers, JPL is owned by NASA an ...
's "
Deep Space 1
''Deep Space 1'' (DS1) was a NASA technology demonstration spacecraft which flew by an asteroid and a comet. It was part of the New Millennium Program, dedicated to testing advanced technologies.
Launched on 24 October 1998, the ''Deep Space ...
", an award-winning Common Lisp program for autopiloting the
Deep Space One spaceship.
* SigLab, a Common Lisp platform for signal processing used in missile defense, built by
Raytheon
Raytheon Technologies Corporation is an American multinational aerospace and defense conglomerate headquartered in Arlington, Virginia. It is one of the largest aerospace and defense manufacturers in the world by revenue and market capitali ...
.
* NASA's
Mars Pathfinder
''Mars Pathfinder'' (''MESUR Pathfinder'') is an American robotic spacecraft that landed a base station with a roving probe on Mars in 1997. It consisted of a lander, renamed the Carl Sagan Memorial Station, and a lightweight, wheeled robot ...
Mission Planning System.
* SPIKE, a scheduling system for Earth or space based observatories and satellites, notably the
Hubble Space Telescope
The Hubble Space Telescope (often referred to as HST or Hubble) is a space telescope that was launched into low Earth orbit in 1990 and remains in operation. It was not the first space telescope, but it is one of the largest and most vers ...
, written in Common Lisp.
* Common Lisp has been used for prototyping the garbage collector of Microsoft's
.NET Common Language Runtime.
* The original version of
Reddit
Reddit (; stylized in all lowercase as reddit) is an American social news aggregation, content rating, and discussion website. Registered users (commonly referred to as "Redditors") submit content to the site such as links, text posts, imag ...
, though the developers later switched to
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
due to the lack of libraries for Common Lisp, according to an official blog post by Reddit co-founder
Steve Huffman
Steve Huffman, also known by his Reddit username spez (), is an American web developer and entrepreneur. He is the co-founder and CEO of Reddit, a social news and discussion website, which ranks in the top 20 websites in the world. He also co ...
.
There also exist open-source applications written in Common Lisp, such as:
*
ACL2
ACL2 ("A Computational Logic for Applicative Common Lisp") is a software system consisting of a programming language, created by Timothy Still it was an extensible theory in a first-order logic, and an automated theorem prover. ACL2 is designed t ...
, a full-featured
automated theorem prover for an
applicative variant of Common Lisp.
*
Axiom, a sophisticated
computer algebra system
A computer algebra system (CAS) or symbolic algebra system (SAS) is any mathematical software with the ability to manipulate mathematical expressions in a way similar to the traditional manual computations of mathematicians and scientists. The d ...
.
*
Maxima, a sophisticated
computer algebra system
A computer algebra system (CAS) or symbolic algebra system (SAS) is any mathematical software with the ability to manipulate mathematical expressions in a way similar to the traditional manual computations of mathematicians and scientists. The d ...
, based on Macsyma.
*
OpenMusic
OpenMusic (OM) 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. At a more specialized level, a set of provided classes ...
, an object-oriented visual programming environment based on Common Lisp, used in
Computer assisted composition.
* Pgloader, a data loader for
PostgreSQL, which was re-written from Python to Common Lisp.
*
Stumpwm
StumpWM is a tiling window manager that was created when developer Shawn Betts found ratpoison growing increasingly large and " lispy". Intended as a successor to ratpoison, StumpWM is released under the terms of the GPL-2.0-or-later license.
...
, a tiling, keyboard driven X11 Window Manager written entirely in Common Lisp.
See also
*''
Common Lisp the Language
''Common Lisp the Language'' is a reference book by Guy L. Steele about a set of technical standards and programming languages named Common Lisp.
History Before standardizing
The first edition (Digital Press, 1984; ; 465 pages) was written by Guy ...
''
*''
On Lisp''
*''
Practical Common Lisp''
References
Bibliography
A chronological list of books published (or about to be published) about Common Lisp (the language) or about programming with Common Lisp (especially AI programming).
*
Guy L. Steele: ''Common Lisp the Language, 1st Edition'', Digital Press, 1984,
*
Rodney Allen Brooks: ''Programming in Common Lisp'', John Wiley and Sons Inc, 1985,
*
Richard P. Gabriel: ''Performance and Evaluation of Lisp Systems'', The MIT Press, 1985,
PDF*
Robert Wilensky
Robert Wilensky (26 March 1951 – 15 March 2013) was an American computer scientist and emeritus professor at the UC Berkeley School of Information, with his main focus of research in artificial intelligence.
Academic career
In 1971, Wilens ...
: ''Common LISPcraft'', W.W. Norton & Co., 1986,
*
Eugene Charniak
Eugene Charniak is a professor of computer Science and cognitive Science at Brown University. He holds an A.B. in Physics from the University of Chicago and a Ph.D. from M.I.T. in Computer Science. His research has always been in the area of l ...
,
Christopher K. Riesbeck,
Drew V. McDermott,
James R. Meehan: ''Artificial Intelligence Programming, 2nd Edition'', Lawrence Erlbaum, 1987,
*
Wendy L. Milner: ''Common Lisp: A Tutorial'', Prentice Hall, 1987,
*
Deborah G. Tatar: ''A Programmer's Guide to Common Lisp'', Longman Higher Education, 1987,
*
Taiichi Yuasa,
Masami Hagiya: ''Introduction to Common Lisp'', Elsevier Ltd, 1987,
*
Christian Queinnec,
Jerome Chailloux: ''Lisp Evolution and Standardization'', Ios Pr Inc., 1988,
*
Taiichi Yuasa,
Richard Weyhrauch,
Yasuko Kitajima: ''Common Lisp Drill'', Academic Press Inc, 1988,
*
Wade L. Hennessey: ''Common Lisp'', McGraw-Hill Inc., 1989,
*
Tony Hasemer,
John Dominque: ''Common Lisp Programming for Artificial Intelligence'', Addison-Wesley Educational Publishers Inc, 1989,
*
Sonya E. Keene: ''Object-Oriented Programming in Common Lisp: A Programmer's Guide to CLOS'', Addison-Wesley, 1989,
*
David Jay Steele: ''Golden Common Lisp: A Hands-On Approach'', Addison Wesley, 1989,
*
David S. Touretzky: ''Common Lisp: A Gentle Introduction to Symbolic Computation'', Benjamin-Cummings, 1989,
Web/PDFDover reprint (2013)
*
Christopher K. Riesbeck,
Roger C. Schank: ''Inside Case-Based Reasoning'', Lawrence Erlbaum, 1989,
*
Patrick Winston
Patrick Henry Winston (February 5, 1943 – July 19, 2019) was an American computer scientist and professor at the Massachusetts Institute of Technology. Winston was director of the MIT Artificial Intelligence Laboratory from 1972 to 1997, succ ...
,
Berthold Horn: ''Lisp, 3rd Edition'', Addison-Wesley, 1989,
Web*
Gerard Gazdar,
Chris Mellish: ''Natural Language Processing in LISP: An Introduction to Computational Linguistics'', Addison-Wesley Longman Publishing Co., 1990,
*
Patrick R. Harrison: ''Common Lisp and Artificial Intelligence'', Prentice Hall PTR, 1990,
*
Timothy Koschmann: ''The Common Lisp Companion'', John Wiley & Sons, 1990,
*
W. Richard Stark: ''LISP, Lore, and Logic'', Springer Verlag New York Inc., 1990,
PDF*
Molly M. Miller,
Eric Benson: ''Lisp Style & Design'', Digital Press, 1990,
*
Guy L. Steele: ''
Common Lisp the Language
''Common Lisp the Language'' is a reference book by Guy L. Steele about a set of technical standards and programming languages named Common Lisp.
History Before standardizing
The first edition (Digital Press, 1984; ; 465 pages) was written by Guy ...
, 2nd Edition'', Digital Press, 1990,
Web* Robin Jones,
Clive Maynard, Ian Stewart: ''The Art of Lisp Programming'', Springer Verlag New York Inc., 1990,
PDF*
Steven L. Tanimoto: ''The Elements of Artificial Intelligence Using Common Lisp'', Computer Science Press, 1990,
*
Peter Lee: ''Topics in Advanced Language Implementation'', The MIT Press, 1991,
*
John H. Riley: ''A Common Lisp Workbook'', Prentice Hall, 1991,
*
Peter Norvig
Peter Norvig (born December 14, 1956) is an American computer scientist and Distinguished Education Fellow at the Stanford Institute for Human-Centered AI. He previously served as a director of research and search quality at Google. Norvig is t ...
: ''Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'', Morgan Kaufmann, 1991,
Web*
Gregor Kiczales
Gregor Kiczales is an American computer scientist. He is currently a full time professor of computer science at the University of British Columbia in Vancouver, British Columbia, Canada. He is best known for developing the concept of aspect-orien ...
,
Jim des Rivieres
Jim or JIM may refer to:
* Jim (given name), a given name
* Jim, a diminutive form of the given name James
* Jim, a short form of the given name Jimmy
* OPCW-UN Joint Investigative Mechanism
* ''Jim'' (comics), a series by Jim Woodring
* ''Ji ...
,
Daniel G. Bobrow: ''The Art of the Metaobject Protocol'', The MIT Press, 1991,
*
Jo A. Lawless,
Molly M. Miller: ''Understanding CLOS: The Common Lisp Object System'', Digital Press, 1991,
* Mark Watson: ''Common Lisp Modules: Artificial Intelligence in the Era of Neural Networks and Chaos Theory'', Springer Verlag New York Inc., 1991,
PDF*
James L. Noyes: ''Artificial Intelligence with Common Lisp: Fundamentals of Symbolic and Numeric Processing'', Jones & Bartlett Pub, 1992,
*
Stuart C. Shapiro: ''COMMON LISP: An Interactive Approach'', Computer Science Press, 1992,
Web/PDF*
Kenneth D. Forbus,
Johan de Kleer: ''Building Problem Solvers'', The MIT Press, 1993,
*
Andreas Paepcke
Andreas ( el, Ἀνδρέας) is a name usually given to males in Austria, Greece, Cyprus, Denmark, Armenia, Estonia, Ethiopia, Eritrea, Finland, Flanders, Germany, Norway, Sweden, Switzerland, Romania, the Netherlands, and Indonesia. The name ...
: ''Object-Oriented Programming: The CLOS Perspective'', The MIT Press, 1993,
*
Paul Graham: ''
On Lisp'', Prentice Hall, 1993,
Web/PDF*
Paul Graham: ''ANSI Common Lisp'', Prentice Hall, 1995,
*
Otto Mayer: ''Programmieren in Common Lisp'', German, Spektrum Akademischer Verlag, 1995,
*
Stephen Slade: ''Object-Oriented Common Lisp'', Prentice Hall, 1997,
*
Richard P. Gabriel: ''Patterns of Software: Tales from the Software Community'', Oxford University Press, 1998,
PDF*
Taiichi Yuasa,
Hiroshi G. Okuno: ''Advanced Lisp Technology'', CRC, 2002,
*
David B. Lamkins: ''Successful Lisp: How to Understand and Use Common Lisp'', bookfix.com, 2004.
Web*
Peter Seibel: ''
Practical Common Lisp'', Apress, 2005.
Web*
Doug Hoyte: ''Let Over Lambda'', Lulu.com, 2008,
Web*
George F. Luger,
William A. Stubblefield: ''AI Algorithms, Data Structures, and Idioms in Prolog, Lisp and Java'', Addison Wesley, 2008,
PDF*
Conrad Barski: ''Land of Lisp: Learn to program in Lisp, one game at a time!'', No Starch Press, 2010,
Web*
Pavel Penev: ''Lisp Web Tales'', Leanpub, 2013
Web*
Edmund Weitz: ''Common Lisp Recipes'', Apress, 2015,
Web*
Patrick M. Krusenotto: ''Funktionale Programmierung und Metaprogrammierung, Interaktiv in Common Lisp'', Springer Fachmedien Wiesbaden 2016,
Web
External links
Quicklisp- A very popular and high quality library manager for Common Lisp
* Th
Awesome CLlist, a curated list of Common Lisp frameworks and libraries.
* Th
Common Lisp Cookbook a collaborative project.
* Th
CLiki a Wiki for
free and open-source Common Lisp systems running on Unix-like systems.
* One of the main repositories for free Common Lisp for software i
Common-Lisp.net
lisp-lang.orghas documentation and a showcase of success stories.
* An overview of the history of Common Lisp:
Common Lisp Quick Reference– a compact overview of the Common Lisp standard language.
Planet LispArticles about Common Lisp.
Quickdocssummarizes documentation and dependency information for many Quicklisp projects.
{{Authority control
Articles with example Lisp (programming language) code
Class-based programming languages
Cross-platform free software
Cross-platform software
Dynamic programming languages
Dynamically typed programming languages
Extensible syntax programming languages
Functional languages
Lisp (programming language)
Lisp programming language family
Multi-paradigm programming languages
Object-oriented programming languages
Procedural programming languages
Programming languages created in 1984