Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language
Programming language
A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer.... , published in ANSI
American National Standards Institute
The American National Standards Institute or 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.... standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 (R1999). Developed to standardize the divergent variants of Lisp which predated it, it is not an implementation but rather a language specification. Several implementations of the Common Lisp standard are available, including proprietary products and open source software.
A multi-paradigm programming language is a programming language that supports more than one programming paradigm. As Lead designer Tim Budd holds it: The idea of a multiparadigm language is to provide a framework in which programmers can work in a variety of styles, freely intermixing constructs from different paradigms. The design goal... .
Discussion
Ask a question about 'Common Lisp'
Start a new discussion about 'Common Lisp'
Answer questions from other users
Full Discussion Forum
Encyclopedia
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language
Programming language
A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer.... , published in ANSI
American National Standards Institute
The American National Standards Institute or 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.... standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 (R1999). Developed to standardize the divergent variants of Lisp which predated it, it is not an implementation but rather a language specification. Several implementations of the Common Lisp standard are available, including proprietary products and open source software.
A multi-paradigm programming language is a programming language that supports more than one programming paradigm. As Lead designer Tim Budd holds it: The idea of a multiparadigm language is to provide a framework in which programmers can work in a variety of styles, freely intermixing constructs from different paradigms. The design goal... . It supports a combination of procedural
Procedural programming
Procedural programming can sometimes be used as a synonym for imperative programming , but can also refer to a programming paradigm based upon the concept of the procedure call.... , functional
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of function s and avoids program state and immutable object data.... and object-oriented programming paradigms. As a dynamic programming language
Dynamic programming language
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compiler, if at all.... , it facilitates rapid development, with iterative compilation
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language . The most common reason for wanting to transform source code is to create an executable program.... into efficient run-time programs.
Common Lisp includes CLOS, an object system that supports multimethods and method combinations. It is extensible through standard features such as Lisp macros (compile-time code rearrangement accomplished by the program itself) and reader macros (extension of syntax to give special meaning to characters reserved for users for this purpose).
Syntax
Common Lisp is a dialect of Lisp; it uses S-expression
S-expression
The term S-expression or sexp refers to a convention for representing semi-structured data in human-readable textual form. S-expressions are probably best known for their use in the Lisp programming language family of programming languages.... s to denote both code and data structure. Function and macro calls are written as lists, with the name of the function first, as in these examples:
(+ 2 2) ; adds 2 and 2, yielding 4.
(defvar *x*) ; Ensures that a variable *x* exists,
; without giving it a value. The asterisks are part of
; the name. The symbol *x* is also hereby endowed with
; the property that subsequent bindings of it are dynamic,
; rather than lexical.
(setf *x* 42.1) ; sets the variable *x* to the floating-point value 42.1
;; Define a function that squares a number:
(defun square (x)
(* x x))
;; Execute the function:
(square 3); Returns 9
;; the 'let' construct creates a scope for local variables. Here
;; the variable 'a' is bound to 6 and the variable 'b' is bound
;; to 4. Inside the 'let' is a 'body', where the last computed value is returned.
;; Here the result of adding a and b is returned from the 'let' expression.
;; The variables a and b have lexical scope, unless the symbols have been
;; marked as special variables (for instance by a prior DEFVAR).
(let ((a 6)
(b 4))
(+ a b)); returns 10
Data types
Common Lisp has many data types, more than many other languages.
The integers are natural numbers including 0 and their negative and non-negative numberss . They are numbers that can be written without a fractional or decimal component, and fall within the set .... s, ratio
Ratio
A ratio is an expression which compares quantities relative to each other. The most common examples involve two quantities, but in theory any number of quantities can be compared.... s, floating-point number
Floating point
In computing, floating point describes a system for numerical representation in which a String of digits represents a rational number.The term floating point refers to the fact that the radix point can "float": that is, it can be placed anywhere relative to the Significant figures of the number.... s, and complex number
Complex number
In mathematics, the complex numbers are an extension of the real numbers obtained by adjoining an imaginary unit, denoted i, which satisfies:... s. Common Lisp uses bignum
Arbitrary-precision arithmetic
In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, is a technique whereby computer programs perform calculations on integers or rational numbers with an arbitrary number of numerical digits of precision , typically limited only by the available memory of the host system.... 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.
In computer and machine-based telecommunications terminology, a character is a unit of information that roughly corresponds to a grapheme, grapheme-like unit, or symbol, such as in an alphabet or syllabary in the written language form of a natural language.... type is not limited to ASCII
ASCII
American Standard Code for Information Interchange , is a coding standard that can be used for interchanging information, if the information is expressed mainly by the written form of English words.... characters. Most modern implementations allow Unicode
Unicode
Unicode is a computing industry standard allowing computers to consistently represent and manipulate Character expressed in most of the world's writing systems.... characters.
A symbol is something such as an entity, picture, written word, sound, or particular mark that represents something else by association, resemblance, or convention.... type is common to Lisp languages, but largely unknown outside them. A symbol is a unique, named data object with several parts: name, value, function, property list and package. Of these, value cell and function cell are the most important. Symbols in Lisp are often used similarly to identifiers in other languages: to hold value of a variable; however there are many other uses. Normally, when a symbol is evaluated, its value is returned. Some symbols evaluate to themselves, for example all symbols in 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'.
Data structures
Sequence types in Common Lisp include lists, vectors, bit-vectors, and strings. There are many operations which can work on any sequence type.
As in almost all other Lisp dialects, lists in Common Lisp are composed of conses, sometimes called cons cells or pairs. A cons is a data structure with two slots, called its car and cdr. A list is a linked chain of conses. Each cons's car refers to a member of the list (possibly another list). Each cons's cdr refers to the next cons -- except for the last cons, whose cdr refers to the nil value. Conses can also easily be used to implement trees and other complex data structures; though it is usually advised to use structure
or class instances instead. It is also possible to create circular data structures with conses.
Common Lisp supports multidimensional arrays, and can dynamically resize arrays if required. Multidimensional arrays can be used for matrix mathematics. A vector is a one-dimensional array. Arrays can carry any type as members (even mixed types in the same array) or can be specialized to contain a specific type of members, as in a vector of integers. Many implementations can optimize array functions when the array used is type-specialized. Two type-specialized array types are standard: a string is a vector of characters, while a bit-vector is a vector of bit
Bit
A bit is a binary numeral system numerical digit, taking a value of either 0 or 1. Binary digits are a basic unit of information Computer data storage and transmission in digital computing and digital information theory.... s.
In computer science, a hash table, or a hash map, is a data structure that associates Unique key with value .The primary operation that hash functions support efficiently is a lookup: given a key , find the corresponding value .... s store associations between data objects. Any object may be used as key or value. Hash tables, like arrays, are automatically resized as needed.
Packages are collections of symbols, used chiefly to separate the parts of a program into namespaces
Namespace (computer science)
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols . An identifier defined in a namespace is associated with that namespace.... . A package may export some symbols, marking them as part of a public interface. Packages can use other packages.
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... 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.) Classes have been added late to Common Lisp and there is some conceptual overlap with structures. Objects created of classes are called Instances. A special case are Generic Functions. Generic Functions are both functions and instances.
In computer science, a programming language is said to support first-class functions if it treats function s as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning the... s. For instance, it is possible to write functions that take other functions as arguments or return functions as well. This makes it possible to describe very general operations.
The Common Lisp library relies heavily on such higher-order functions. For example, the sort function takes a relational operator
Relational operator
In computer science a relational operator is a programming language construct or Operator that tests some kind of relation between Binary function.... 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.
(sort (list 5 2 6 3 1 4) #'>)
; Sorts the list using the > function as the relational operator.
; Returns (6 5 4 3 2 1).
(sort (list '(9 A) '(3 B) '(4 C)) #'< :key #'first)
; Sorts the list according to the first element of each sub-list.
; Returns ((3 B) (4 C) (9 A)).
The evaluation model for functions is very simple. When the evaluator encounters a form (F A1 A2...) then it is to assume that the symbol named F is one of the following:
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.
A function definition gives the name of the function, the names of any arguments, and a function body:
(defun square (x)
(* x x))
Function definitions may include declarations, which provide hints to the compiler about optimization settings or the data types of arguments. They may also include documentation strings (docstrings), which the Lisp system may use to provide interactive documentation:
(defun square (x)
"Calculates the square of the single-float x."
(declare (single-float x) (optimize (speed 3) (debug 0) (safety 1)))
(* x x))
Anonymous functions (function literals) are defined using lambda expressions, e.g. (lambda (x) (* x x)) for a function that squares its argument. Lisp programming style frequently uses higher-order functions for which it is useful to provide anonymous functions as arguments.
Local functions can be defined with flet and labels.
(flet ((square (x)
(* x x)))
(square 3))
There are a number of other operators related to the definition and manipulation of functions. For instance, a function may be recompiled with the compile operator. (Some Lisp systems run functions in an interpreter by default unless instructed to compile; others compile every entered function on the fly.)
Defining generic functions and methods
The macro defgeneric defines generic functions.
The macro defmethod defines methods. Generic functions are a collection of methods.
Methods can specialize their parameters over classes or objects.
When a generic function is called, multiple-dispatch will determine the correct method to use.
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. Operators which 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 #'>.
Scheme's evaluation model is simpler: there is only one namespace, and all positions in the form are evaluated (in any order) -- not just the arguments. Code written in one dialect is therefore sometimes confusing to programmers more experienced in the other. For instance, many Common Lisp programmers like to use descriptive variable names such as list or string which could cause problems in Scheme as they would locally shadow function names.
Whether a separate namespace for functions is an advantage is a source of contention in the Lisp community. It is usually referred to as the Lisp-1 vs. Lisp-2 debate. Lisp-1 refers to Scheme's model and Lisp-2 refers to Common Lisp's model. These names were coined in a 1988 paper by Richard P. Gabriel and Kent Pitman
Kent Pitman
Kent M. Pitman is the President of and has been involved for many years in the design, implementation and use of Lisp programming language and Scheme systems.... , which extensively compares the two approaches.
Other types
Other data types in Common Lisp include:
Pathnames represent files and directories in the filesystem. The Common Lisp pathname facility is more general than most operating systems' file naming conventions, making Lisp programs' access to files broadly portable across diverse systems.
Input and output streams represent sources and sinks of binary or textual data, such as the terminal or open files.
Common Lisp has a built-in pseudo-random number generator (PRNG). Random state objects represent reusable sources of pseudo-random numbers, allowing the user to seed the PRNG or cause it to replay a sequence.
Conditions are a type used to represent errors, exceptions, and other "interesting" events to which a program may respond.
Classes are first-class objects, and are themselves instances of classes called metaclasses.
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 is 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 (but, in recognition of the usefulness of dynamically scoped function bindings, a portable library exists now which provides them).
Dynamic scope is extremely useful because it adds referential clarity and discipline to global variable
Global variable
In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms.... s. Global variables are frowned upon in computer science as potential sources of error, because they can give rise to ad-hoc, covert channels of communication among modules that lead to unwanted, surprising interactions.
In Common Lisp, a special variable which has only a top-level binding behaves just like a global variable in other programming languages. A new value can be stored into it, and that value simply replaces what is in the top-level binding. Careless replacement of the value of a global variable is at the heart of bugs caused by use of global variables. However, another way to work with a special variable is to give it a new, local binding within an expression. This is sometimes referred to as "rebinding" the variable. Binding a dynamically scoped variable temporarily creates a new memory location for that variable, and associates the name with that location. While that binding is in effect, all references to that variable refer to the new binding; the previous binding is hidden. When execution of the binding expression terminates, the temporary memory location is gone, and the old binding is revealed, with the original value intact. Of course, multiple dynamic bindings for the same variable can be nested.
In Common Lisp implementations which support multithreading, dynamic scopes are specific to each thread of execution. Thus special variables serve as an abstraction for thread local storage. If one thread rebinds a special variable, this rebinding has no effect on that variable in other threads. The value stored in a binding can only be retrieved by the thread which created that binding. If each thread binds some special variable *X*, then *X* behaves like thread-local storage. Among threads which do not rebind *X*, it behaves like an ordinary global: all of these threads refer to the same top-level binding of *X*.
Dynamic variables can be used to extend the execution context with additional context information which is implicitly passed from function to function without having to appear as an extra function parameter. This is especially useful when the control transfer has to pass through layers of unrelated code, which simply cannot be extended with extra parameters to pass the additional data. A situation like this usually calls for a global variable. That global variable must be saved and restored, so that the scheme doesn't break under recursion: dynamic variable rebinding take care of this. And that variable must be made thread-local (or else a big mutex must be used) so the scheme doesn't break under threads: dynamic scope implementations can take care of this also.
In the Common Lisp library, there are many standard special variables. For instance, the all standard I/O streams are stored in the top-level bindings of well-known special variables. The standard output stream is stored in *standard-output*.
Suppose a function foo writes to standard output:
(defun foo
(format t "Hello, world"))
It would be nice to capture its output in a character string. No problem, just rebind *standard-output* to a string stream and call it:
(with-output-to-string (*standard-output*)
(foo))
-> "Hello, world" ; gathered output returned as a string
Lexical
Common Lisp supports lexical environments. Formally, the bindings in a lexical environment have lexical scope and may have either indefinite extent or dynamic extent, depending on the type of namespace. Lexical scope means that visibility is physically restricted to the block in which the binding is established. References which are not textually (i.e. lexically) embedded in that block simply do not see that binding.
The tags in a TAGBODY have lexical scope. The expression (GO X) is erroneous if it is not actually embedded in a TAGBODY which contains a label X. However, the label bindings disappear when the TAGBODY terminates its execution, because they have dynamic extent. If that block of code is re-entered by the invocation of a lexical closure, it is invalid for the body of that closure to try to transfer control to a tag via GO:
When the TAGBODY is executed, it first evaluates the setf form which stores a function in the special variable *stashed*. Then the (go end-label) transfers control to end-label, skipping the code (print "Hello"). Since end-label is at the end of the tagbody, the tagbody terminates, yielding NIL. Suppose that the previously remembered function is now called:
(funcall *stashed*) ;; Error!
This situation is erroneous. One implementation's response is an error condition containing the message, "GO: tagbody for tag SOME-LABEL has already been left". The function tried to evaluate (go some-label), which is lexically embedded in the tagbody, and resolves to the label. However, the tagbody isn't executing (its extent has ended), and so the control transfer cannot take place.
Local function bindings in Lisp have lexical scope, and variable bindings also have lexical scope by default. By contrast with GO labels, both of these have indefinite extent. When a lexical function or variable binding is established, that binding continues to exist for as long as references to it are possible, even after the construct which established that binding has terminated. References to a lexical variables and functions after the termination of their establishing construct are possible thanks to lexical closures.
Lexical binding is the default binding mode for Common Lisp variables. For an individual symbol, it can be switched to dynamic scope, either by a local declaration, by a global declaration. The latter may occur implicitly through the use of a construct like DEFVAR or DEFPARAMETER. It is an important convention in Common Lisp programming that special (i.e. dynamically scoped) variables have names which begin and end with an asterisk. If adhered to, this convention effectively creates a separate namespace for special variables, so that variables intended to be lexical are not accidentally made special.
Lexical scope is useful for several reasons.
Firstly, references to variables and functions can be compiled to efficient machine code, because the run-time environment structure is relatively simple. In many cases it can be optimized to stack storage, so opening and closing lexical scopes has minimal overhead. Even in cases where full closures must be generated, access to the closure's environment is still efficient; typically each variable becomes an offset into a vector of bindings, and so a variable reference becomes a simple load or store instruction with a base-plus-offset addressing mode
Addressing mode
Addressing modes are an aspect of the instruction set architecture in most central processing unit designs. The various addressing modes that are defined in a given instruction set architecture define how Machine code Instruction in that architecture identify the operand of each instruction.... .
Secondly, lexical scope (combined with indefinite extent) gives rise to the lexical closure, which in turn creates a whole paradigm of programming centered around the use of functions being first-class objects, which is at the root of functional programming.
Thirdly, perhaps most importantly, even if lexical closures are not exploited, the use of lexical scope isolates program modules from unwanted interactions. Due to their restricted visibility, lexical variables are private. If one module A binds a lexical variable X, and calls another module B, references to X in B will not accidentally resolve to the X bound in A. B simply has no access to X. For situations in which disciplined interactions through a variable are desirable, Common Lisp provides special variables. Special variables allow for a module A to set up a binding for a variable X which is visible to another module B, called from A. Being able to do this is an advantage, and being able to prevent it from happening is also an advantage; consequently, Common Lisp supports both lexical and dynamic scope.
Macros
A macro in Lisp superficially resembles a function in usage. However, rather than representing an expression which is evaluated, it represents a transformation of the program source code.
Macros allow Lisp programmers to create new syntactic forms in the language. For instance, this macro provides the until loop form, which may be familiar from languages such as Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... :
(defmacro until (test &body body)
`(do
(test)
,@body))
;; example
(until (= (random 10) 0)
(write-line "Hello"))
All macros must be expanded before the source code containing them can be evaluated or compiled normally. Macros can be considered functions that
accept and return abstract syntax tree
Abstract syntax tree
In computer science, an abstract syntax tree , or just syntax tree, is a directed tree representation of the abstract syntactic structure of source code written in a certain programming language.... s (Lisp S-expressions). These functions
are invoked before the evaluator or compiler to produce the final source code.
Macros are written in normal Common Lisp, and may use any Common Lisp (or third-party) operator available. The backquote notation used above is provided
by Common Lisp specifically to simplify the common case of substitution into
a code template.
Variable capture and shadowing
Common Lisp macros are capable of what is commonly called variable capture, where symbols in the macro-expansion body coincide with those in the calling context, allowing the programmer to create macros wherein various symbols have special meaning. The term variable capture is somewhat misleading, because all namespaces are vulnerable to unwanted capture, including the operator and function namespace, the tagbody label namespace, catch tag, condition handler and restart namespaces.
Variable capture can introduce software defects. This happens in one of the following two ways:
In the first way, a macro expansion can inadvertently make a symbolic reference which the macro writer assumed will resolve in a global namespace, but the code where the macro is expanded happens to provide a local, shadowing definition it which steals that reference. Let this be referred to as type 1 capture.
The second way, type 2 capture, is just the opposite: some of the arguments of the macro are pieces of code supplied by the macro caller, and those pieces of code are written such that they make references to surrounding bindings. However, the macro inserts these pieces of code into an expansion which defines its own bindings that accidentally captures some of these references.
The Scheme dialect of Lisp provides a macro-writing system which provides the referential transparency that eliminates both types of capture problem. This type of macro system is sometimes called "hygienic", in particular by its proponents (who regard macro systems which do not automatically solve this problem as unhygienic).
In Common Lisp, macro hygiene is ensured one of two different ways.
One approach is to use gensyms: guaranteed-unique symbols which can be used in a macro-expansion without threat of capture. The use of gensyms in a macro definition is a manual chore, but macros can be written which simplify the instantiation and use of gensyms. Gensyms solve type 2 capture easily, but they are not applicable to type 1 capture in the same way, because the macro expansion cannot rename the interfering symbols in the surrounding code which capture its references. Gensyms could be used to provide stable aliases for the global symbols which the macro expansion needs. The macro expansion would use these secret aliases rather than the well-known names, so redefinition of the well-known names would have no ill effect on the macro.
Another approach is to use packages. A macro defined in its own package can simply use internal symbols in that package in its expansion. The use of packages deals with type 1 and type 2 capture.
However, packages don't solve the type 1 capture of references to standard Common Lisp functions and operators. The reason is that the use of packages to solve capture problems revolves around the use of private symbols (symbols in one package, which are not imported into, or otherwise made visible in other packages). Whereas the Common Lisp library symbols are external, and frequently imported into or made visible in user-defined packages.
The following is an example of unwanted capture in the operator namespace, occurring in the expansion of a macro:
;; expansion of UNTIL makes liberal use of DO
(defmacro until (expression &body body)
`(do (expression) ,@body))
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.
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... , the Common Lisp Object System or CLOS, which is one of the most powerful object systems available in any language. Originally proposed as an add-on, CLOS was adopted as part of the ANSI standard for Common Lisp. CLOS is a dynamic
Dynamic programming language
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compiler, if at all.... object system with multiple dispatch
Multiple dispatch
Multiple dispatch or multimethods is the feature of some object-oriented programming languages in which a function or method can be dynamically dispatched based on the run time type of more than one of its arguments.... and multiple inheritance
Multiple inheritance
Multiple inheritance refers to a feature of some object-oriented programming programming languages in which a class can inheritance behaviors and features from more than one superclass .... , and differs radically from the OOP facilities found in static languages such as C++
C++
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features.... or Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java .... . As a dynamic object system, CLOS allows changes at runtime to generic functions and classes. Methods can be added and removed, classes can be added and redefined, objects can be updated for class changes and the class of objects can be changed.
CLOS has been integrated into ANSI Common Lisp. Generic Functions can be used like normal functions and are a first-class data type. Every CLOS class is integrated into the Common Lisp type system. Many Common Lisp types have a corresponding class. There is more potential use of CLOS for Common Lisp. The specification does not say whether conditions are implemented with CLOS. Pathnames and streams could be implemented with CLOS. These further usage possibilities of CLOS for ANSI Common Lisp are not part of the standard. Actual Common Lisp implementations are using CLOS for pathnames, streams, input/output, conditions, the implementation of CLOS itself and more.
Comparison with other Lisps
Common Lisp is most frequently compared with, and contrasted to, Scheme—if only because they are the two most popular Lisp dialects. Scheme predates CL, and comes not only from the same Lisp tradition but from some of the same engineers—Guy L. Steele
Guy L. Steele, Jr.
Guy Lewis Steele Jr., , also known as "The Great Quux" and GLS , is an American computer scientist who has played an important role in designing and documenting several computer programming languages.... , with whom Gerald Jay Sussman
Gerald Jay Sussman
Gerald Jay Sussman is the Panasonic Professor of Electrical engineering at the Massachusetts Institute of Technology . He received his Bachelor of Science and Doctor of Philosophy degrees in mathematics from MIT in 1968 and 1973 respectively.... designed Scheme, chaired the standards committee for Common Lisp.
Common Lisp is a general-purpose programming language, in contrast to Lisp variants such as Emacs Lisp
Emacs Lisp
Emacs Lisp is a dialect of the Lisp programming language used by the GNU Emacs and XEmacs text editors . It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C .... and AutoLISP
AutoLISP
AutoLISP is a dialect of Lisp programming language built specifically for use with the full version of AutoCAD and its derivatives, which include Autodesk Map 3D and Autodesk Architectural Desktop.... which are embedded extension languages in particular products. Unlike many earlier Lisps, Common Lisp (like Scheme) uses lexical variable scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes.... .
Most of the Lisp systems whose designs contributed to Common Lisp—such as ZetaLisp
ZetaLisp
ZetaLisp was the name Symbolics gave to their dialect of Lisp programming language on their Lisp Machine models, to distinguish it from the MIT version, which was called Lisp Machine Lisp.... and Franz Lisp—used dynamically scoped
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes.... variables in their interpreters and lexically scoped variables in their compilers. Scheme introduced the sole use of lexically-scoped variables to Lisp; an inspiration from ALGOL 68
ALGOL 68
ALGOL 68 is an imperative programming computer programming 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 defined syntax and semantics.... which was widely recognized as a good idea. CL supports dynamically-scoped variables as well, but they must be explicitly declared as "special". There are no differences in scoping between ANSI CL interpreters and compilers.
Common Lisp is sometimes termed a Lisp-2 and Scheme a Lisp-1, referring to CL's use of separate namespaces for functions and variables. (In fact, CL has many namespaces, such as those for go tags, block names, and loop keywords.) There is a long-standing controversy between CL and Scheme advocates over the tradeoffs involved in multiple namespaces. In Scheme, it is (broadly) necessary to avoid giving variables names which clash with functions; Scheme functions frequently have arguments named lis, lst, or lyst so as not to conflict with the system function list. However, in CL it is necessary to explicitly refer to the function namespace when passing a function as an argument -- which is also a common occurrence, as in the sort example above.
CL also differs from Scheme in its handling of boolean values. Scheme uses the special values #t and #f to represent truth and falsity. CL follows the older Lisp convention of using the symbols T and NIL, with NIL standing also for the empty list. In CL, any non-NIL value is treated as true by conditionals such as if as are non-#f values in Scheme. This allows some operators to serve both as predicates (answering a boolean-valued question) and as returning a useful value for further computation.
In computer science, tail recursion is a special case of Recursion_ in which the last operation of the function, the tail call, is a recursive call.... , which the CL standard does not. Most CL implementations do offer tail-call optimization, although often only when the programmer uses an optimization directive. Nonetheless, common CL coding style does not favor the ubiquitous use of recursion that Scheme style prefers -- what a Scheme programmer would express with tail recursion, a CL user would usually express with an iterative expression in do, dolist, loop, or (more recently) with the iterate package.
Implementations
See the Category Common Lisp implementations.
Common Lisp is defined by a specification (like Ada and C
C (programming language)
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... ) rather than by a single implementation (like Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... prior to version 6). There are many implementations, and the standard spells out areas in which they may validly differ.
In addition, implementations tend to come with library packages, which provide functionality not covered in the standard. Free Software
Free software
Free Software or software libre is software that can be used, studied, and modified without restriction, and which can be copied and redistributed in modified or unmodified form either without restriction, or with minimal restrictions only to ensure that further recipients can also do these things and to prevent consumer-facing hardware... libraries have been created to support such features in a portable way, most notably and the project.
Common Lisp implementations may use any mix of native code compilation, byte code compilation or interpretion. Common Lisp has been designed to support incremental compiler
Incremental compiler
Generally a compiler for a programming language is a piece of software that reads in one or more program files in a source language and outputs one or more files containing machine code or some other low level language.... s, file compilers and block compilers. Standard declarations to optimize compilation (such as function inlining) are proposed in the language specification. Most Common Lisp implementations compile source code to native machine code
Machine code
Machine code or machine language is a system of instructions and data executed directly by a computer's central processing unit. Machine code may be regarded as a primitive programming language or as the lowest-level representation of a compiled and/or assembly language computer program.... . Some implementations can create (optimized) stand-alone applications. Others compile to bytecode
Bytecode
Bytecode is a term which has been used to denote various forms of instruction sets designed for efficient execution by a software Interpreter as well as being suitable for further compilation into machine language.... , which reduces speed but eases binary-code portability. There are also compilers that compile Common Lisp code to C code. The misconception that Lisp is a purely-interpreted language is most likely due to the fact that 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.
Unix is a computer operating system originally developed in 1969 by a group of American Telephone & Telegraph employees at Bell Labs, including Ken Thompson , Dennis Ritchie, Douglas McIlroy, and Joe Ossanna.... -based implementations (CLISP
CLISP
In computing, CLISP is a programming language originally developed by Bruno Haible and Michael Stoll for the Atari ST. Today it supports Unix and Microsoft Windows systems.... , SBCL) can be used as ; that is, invoked by the system transparently in the way that a Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... or Unix shell
Unix shell
A Unix shell is a command-line interpreter and script host that provides a traditional user interface for the Unix operating system and for Unix-like systems.... interpreter is.
Allegro Common Lisp is a commercial implementation of the Common Lisp programming language developed by Franz Inc. Allegro CL provides the full ANSI Common Lisp standard with many extensions....
LispWorks is a commercial implementation and Integrated Development Environment for the Common Lisp programming language. The software runs on Microsoft Windows, Mac OS X, Linux, FreeBSD, and several commercial UNIX systems....
Corman Common Lisp is a commercial implementation of the Common Lisp programming language featuring support for the Windows operating system.... , which is particularly adapted to Microsoft Windows
Scieneer® Common Lisp is a commercial implementation of the Common Lisp programming language featuring support for Symmetric multiprocessing on a range of Linux, Solaris and HP-UX platforms.... , which is designed for high-performance scientific computing.
CMUCL is a free software Common Lisp implementation, originally developed at Carnegie Mellon University.CMUCL runs on most Unix-like platforms, including Linux and Berkeley Software Distribution; there is an experimental Microsoft Windows port as well.... , originally from Carnegie Mellon University
Carnegie Mellon University
Carnegie Mellon University is a top private university research university in Pittsburgh. Since its inception, Carnegie Mellon has grown into a world-renowned institution, with numerous programs that are frequently college and university rankings among the best in the world.... , now maintained as Free Software
Free software
Free Software or software libre is software that can be used, studied, and modified without restriction, and which can be copied and redistributed in modified or unmodified form either without restriction, or with minimal restrictions only to ensure that further recipients can also do these things and to prevent consumer-facing hardware... by a group of volunteers. CMUCL uses a fast native-code compiler. It is available on Linux
Linux
Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed by anyone under the terms of the GNU GPL license... and BSD
Berkeley Software Distribution
Berkeley Software Distribution is the Unix operating system derivative developed and distributed by the Computer Systems Research Group of the University of California, Berkeley, from 1977 to 1995.... for Intel x86; Linux
Linux
Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed by anyone under the terms of the GNU GPL license... for Alpha; Mac OS X
Mac OS X
Mac OS X is a line of computer operating systems developed, marketed, and sold by Apple Inc., and since 2002 has been included with all new Macintosh computer systems.... for Intel x86 and PowerPC; and Solaris, IRIX, and HP-UX on their native platforms.
Steel Bank Common Lisp is a Free software Common Lisp implementation that features ahigh performance native compiler, Unicode support and Thread .... (SBCL), a branch from CMUCL. "Broadly speaking, SBCL is distinguished from CMU CL by a greater emphasis on maintainability." SBCL runs on the platforms CMUCL does, except HP/UX; in addition, it runs on Linux for AMD64, PowerPC, SPARC, and MIPS , and has experimental support for running on Windows. SBCL does not use an interpreter by default; all expressions are compiled to native code unless the user switches the interpreter on.
In computing, CLISP is a programming language originally developed by Bruno Haible and Michael Stoll for the Atari ST. Today it supports Unix and Microsoft Windows systems.... , a bytecode-compiling implementation, portable and runs on a number of Unix and Unix-like systems (including Mac OS X
Mac OS X
Mac OS X is a line of computer operating systems developed, marketed, and sold by Apple Inc., and since 2002 has been included with all new Macintosh computer systems.... ), as well as Microsoft Windows and several other systems.
GNU Common Lisp is the GNU Project's Common Lisp compiler, an evolutionary development of Kyoto Common Lisp. It produces native object code by first generating C and then calling a C compiler.... (GCL), the GNU
GNU
GNU is a computer operating system composed entirely of free software. Its name is a recursive acronym for GNU's Not Unix; it was chosen because its design is Unix-like, but differs from Unix by being free software and containing no Unix code.... Project's Lisp compiler. Not yet fully ANSI-compliant, GCL is however the implementation of choice for several large projects including the mathematical tools Maxima, AXIOM
Axiom
In traditional logic, an axiom or postulate is a proposition that is not proved or demonstrated but considered to be either self-evidence, or subject to necessary decision.... and ACL2. GCL runs on Linux
Linux
Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed by anyone under the terms of the GNU GPL license... under eleven different architectures, and also under Windows, Solaris, and FreeBSD
FreeBSD
FreeBSD is a Unix-like free software operating system descended from AT&T Unix via the Berkeley Software Distribution branch through the 386BSD and Berkeley Software Distribution#4.4BSD and descendants operating systems.... .
Embeddable Common Lisp is a free software Common Lisp implementation aimed at producing a small-footprint Lisp system that can be embedded into existing C -based applications.... (ECL), designed to be embedded in C
C (programming language)
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... programs.
Clozure CL is a Common Lisp software development environment.Clozure CL runs on PowerPC Macintosh computer systems under Mac OS X and Linux, and x86-64 systems under Mac OS X, Linux, and FreeBSD.... , previously “OpenMCL”, a free software
Free software
Free Software or software libre is software that can be used, studied, and modified without restriction, and which can be copied and redistributed in modified or unmodified form either without restriction, or with minimal restrictions only to ensure that further recipients can also do these things and to prevent consumer-facing hardware... / open source
Open-source software
Open source software is defined as computer software for which the source code and certain other rights normally reserved for copyright holders are provided under a computer software license that meets the Open Source Definition or that is in the public domain.... fork of Macintosh Common Lisp. As the name implies, OpenMCL was originally native to the Macintosh. The renamed Clozure CL now runs on Mac OS X
Mac OS X
Mac OS X is a line of computer operating systems developed, marketed, and sold by Apple Inc., and since 2002 has been included with all new Macintosh computer systems.... , Darwin
Darwin (operating system)
Darwin is an open source POSIX-compliant computer operating system released by Apple Inc. in 2000. It is composed of code developed by Apple, as well as code derived from NEXTSTEP, FreeBSD, and other free software projects.... , FreeBSD
FreeBSD
FreeBSD is a Unix-like free software operating system descended from AT&T Unix via the Berkeley Software Distribution branch through the 386BSD and Berkeley Software Distribution#4.4BSD and descendants operating systems.... , and Linux
Linux
Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed by anyone under the terms of the GNU GPL license... for PowerPC and Intel x86-64. A port to Intel x86-32 for the preceding operating systems is in progress, as well as a port to 64-bit Windows.
Movitz is an implementation of the Common Lisp programming language for x86 computers. It runs with no underlying operating system and is intended as "a development platform for operating system kernels, embedded, and single-purpose applications".... implements a Lisp environment for x86 computers without relying on any underlying OS.
Macintosh Common Lisp is an implementation and Integrated Development Environment for the Common Lisp programming language. Various versions of MCL run under Mac OS and Mac OS X .... 5.2 for Apple Macintosh computers with a PowerPC processor running Mac OS X.
Poplog is a powerful multi-Programming language, Multi-paradigm programming language, Reflection , dynamic compilation Computer programming system platform, originally created in the United Kingdom for teaching and research in Artificial Intelligence at the University of Sussex.... system implements a version of CL, with POP-11
POP-11
POP-11 is a powerful Reflection , dynamic compilation programming language with many of the features of an interpreted language. It is the core language of the Poplog Computer programming system platform developed originally by the University of Sussex, and recently in the... , and optionally Prolog
Prolog
Prolog is a logic programming language. It is a general purpose language often associated with artificial intelligence and computational linguistics.... , and Standard ML
Standard ML
Standard ML is a general-purpose, Module , functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of automated theorem proving.... (SML), allowing mixed language programming. For all, the implementation language is POP-11, which is compiled incrementally. It also has an integrated Emacs
Emacs
Emacs is a class of feature-rich text editors, usually characterized by their extensibility. Emacs has, perhaps, more editing commands than any other editor or word processor, numbering over 1,000.... -like editor that communicates with the compiler.
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java .... -oriented
Armed Bear Common Lisp is an implementation of Common Lisp that runs on the Java Virtual Machine. It includes a compiler to Java byte code, and allows access to Java libraries from within Common Lisp.... is a CL implementation that runs on the Java Virtual Machine
Java Virtual Machine
A Java Virtual Machine is a set of computer software programs and data structures which use a virtual machine model for the execution of other computer programs and Scripting language.... . It includes a compiler to Java byte code, and allows access to Java libraries from CL. Armed Bear CL is a component of the , though it can be used independently.
CLforJava is an implementation of Common Lisp in the Java . The project is actively developed at the College of Charleston. It allows for the compilation of Lisp code into Java byte code, and also provides the ability to use Lisp types and code from within Java programs.... is a CL implementation in Java that is actively developed at the College of Charleston
College of Charleston
The College of Charleston is a public university, sea-grant, and space-grant university located in historic downtown Charleston, South Carolina.... .
VAX LISP was an implementation of Common Lisp for OpenVMS and ULTRIX on 32-bit VAXs. It was the first Common Lisp to be written for non-Lisp machines.... - Digital Equipment Corporation
Digital Equipment Corporation
Digital Equipment Corporation was a pioneering United States company in the computer industry. It is often referred to within the computing industry as DEC .... 's implementation that ran on VAX
VAX
VAX was an instruction set architecture developed by Digital Equipment Corporation in the mid-1970s. A 32-bit complex instruction set computer ISA, it was designed to extend or replace DEC's various Programmed Data Processor ISAs.... systems running VMS
OpenVMS
OpenVMS , previously known as VAX-11/VMS, VAX/VMS or VMS, is the name of a high-end computer server operating system that runs on the VAX and DEC Alpha families of computers, developed by Digital Equipment Corporation of Maynard, Massachusetts, Massachusetts , and most recently on Hewlett-Packard systems built around the In... or ULTRIX
Ultrix
Ultrix was the brand name of Digital Equipment Corporation's native Unix systems. While ultrix is the Latin word for avenger, the name was chosen solely for its sound.... .
Applications
See the Category Common Lisp software.
Common Lisp is used in many commercial applications, including the Yahoo!
Yahoo!
Yahoo! Inc. is an United States public company corporation with headquarters in Sunnyvale, California, , and provides Internet services worldwide.... Store web-commerce site, which originally involved Paul Graham
Paul Graham
Paul Graham is a programmer, venture capitalist, and essayist, known for his work on Lisp . He is the author of On Lisp , ANSI Common Lisp , and Hackers & Painters .... and was later rewritten in C++ and Perl. Other notable examples include:
Jak and Daxter is a List of video game franchises originally developed by Naughty Dog for the PlayStation 2. Currently, five games in the series have been released, with Jak as the primary playable character in all except Daxter for the PSP.... video games for Playstation2
OpenMusic is an object-oriented visual programming environment for musical composition based on Common Lisp.It may also be used as an all-purpose visual interface to Lisp programming.... is an object-oriented visual programming environment based on Common Lisp, used in Computer assisted composition
Computer assisted composition
Computer assisted composition is the technique or practice of using a computer to aid in the composition of music, though the music itself may be performed either electronic music or on traditional, non-electronic instruments without the use of a computer or electronic device of any kind.... .
ITA Software is a travel industry software company in Cambridge, Massachusetts. The company was founded by computer scientists from the MIT Computer Science and Artificial Intelligence Laboratory in 1996.... 's low fare search engine, used by travel websites such as Orbitz
Orbitz
Orbitz Worldwide is an Internet travel company headquartered in Chicago, Illinois.Through its primary web site Orbitz.com, Orbitz Worldwide enables travelers to research, plan and book a broad range of travel products.... and Kayak.com
Kayak.com
Kayak.com is a travel search website based in the United States. Founded in 2004, it wikt:aggregate information from over 100 other travel sites and helps users book flights, hotels, cruises, and rental cars.... and airlines such as American Airlines
American Airlines
American Airlines, Inc. is a major carrier of the United States. It is the world's largest airlines in passenger miles transported and passenger fleet size; second largest, behind FedEx Express, in aircraft operated; and second behind Air France-KLM in operating revenues.... , Continental Airlines
Continental Airlines
Continental Airlines, Inc. is a United States certificated Airline. Based in Houston, Texas, it is the fourth-largest airline in the US based on revenue passenger miles.... and US Airways
US Airways
US Airways, Inc., an operating unit of US Airways Group, is the fifth largest airline in the United States. A member of the Star Alliance, it has a fleet of 353 mainline jet aircraft and 319 regional jet and Turboprop aircraft connecting 200 destinations in North America, Central America, the Caribbean, Hawaii, and Europe.... .
There also exist open-source applications written in Common Lisp, such as:
ACL2, a full-featured theorem prover for an applicative variant of Common Lisp.
A computer algebra system is a Application software that facilitates symbolic mathematics. The core functionality of a CAS is manipulation of mathematical expressions in symbolic form.... .
StumpWM is a tiling window manager for POSIX-compliant Unix-like operating systems running the X Window System. It started as a rewrite of the ratpoison window manager.... , a tiling, keyboard driven X11 Window Manager written entirely in Common Lisp.
Practical Common Lisp is an introductory book on Common Lisp by Peter Seibel which intersperses "practical" chapters along with a fairly complete introduction to the language....
Free Software or software libre is software that can be used, studied, and modified without restriction, and which can be copied and redistributed in modified or unmodified form either without restriction, or with minimal restrictions only to ensure that further recipients can also do these things and to prevent consumer-facing hardware... Common Lisp systems running on Unix-like systems.