HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, ( or ) is a fundamental
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
in most dialects of the
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
programming language. ''constructs'' memory objects which hold two values or pointers to two values. These objects are referred to as (cons) cells, conses, non-atomic s-expressions ("NATSes"), or (cons) pairs. In Lisp jargon, the expression "to cons ''x'' onto ''y''" means to construct a new object with (cons ''x'' ''y''). The resulting pair has a left half, referred to as the (the first element, or '' contents of the address part of register''), and a right half, referred to as the (the second element, or '' contents of the decrement part of register''). It is loosely related to the
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
notion of a constructor, which creates a new object given arguments, and more closely related to the constructor function of an
algebraic data type In computer programming, especially functional programming and type theory, an algebraic data type (ADT) is a kind of composite data type, i.e., a data type formed by combining other types. Two common classes of algebraic types are product ty ...
system. The word "cons" and expressions like "to cons onto" are also part of a more general
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declarat ...
jargon. Sometimes
operators Operator may refer to: Mathematics * A symbol indicating a mathematical operation * Logical operator or logical connective in mathematical logic * Operator (mathematics), mapping that acts on elements of a space to produce elements of another ...
that have a similar purpose, especially in the context of list processing, are pronounced "cons". (A good example is the :: operator in ML, Scala, F#, Lean,
Coq Coenzyme Q10 (CoQ10 ), also known as ubiquinone, is a naturally occurring biochemical cofactor (coenzyme) and an antioxidant produced by the human body. It can also be obtained from dietary sources, such as meat, fish, seed oils, vegetables, ...
, and
Elm Elms are deciduous and semi-deciduous trees comprising the genus ''Ulmus'' in the family Ulmaceae. They are distributed over most of the Northern Hemisphere, inhabiting the temperate and tropical- montane regions of North America and Eurasia, ...
or the : operator in
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
, which adds an element to the beginning of a list.)


Use

Although cons cells can be used to hold
ordered pair In mathematics, an ordered pair, denoted (''a'', ''b''), is a pair of objects in which their order is significant. The ordered pair (''a'', ''b'') is different from the ordered pair (''b'', ''a''), unless ''a'' = ''b''. In contrast, the '' unord ...
s of data, they are more commonly used to construct more complex compound data structures, notably lists and
binary tree In computer science, a binary tree is a tree data structure in which each node has at most two children, referred to as the ''left child'' and the ''right child''. That is, it is a ''k''-ary tree with . A recursive definition using set theor ...
s.


Ordered pairs

For example, the Lisp expression constructs a cell holding 1 in its left half (the so-called field) and 2 in its right half (the field). In Lisp notation, the value looks like: (1 . 2) Note the dot between 1 and 2; this indicates that the S-expression is a "dotted pair" (a so-called "cons pair"), rather than a "list."


Lists

In Lisp, lists are implemented on top of cons pairs. More specifically, any list structure in Lisp is either: #An empty list , which is a special object usually called . #A cons cell whose is the first element of the list and whose is a
list A list is a Set (mathematics), set of discrete items of information collected and set forth in some format for utility, entertainment, or other purposes. A list may be memorialized in any number of ways, including existing only in the mind of t ...
containing the rest of the elements. This forms the basis of a simple,
singly linked list In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whic ...
structure whose contents can be manipulated with , , and . Note that is the only list that is not also a cons pair. As an example, consider a list whose elements are 1, 2, and 3. Such a list can be created in three steps: #Cons 3 onto , the empty list #Cons 2 onto the result #Cons 1 onto the result which is equivalent to the single expression: (cons 1 (cons 2 (cons 3 nil))) or its shorthand: (list 1 2 3) The resulting value is the list: (1 . (2 . (3 . nil))) i.e. *--*--*--nil , , , 1 2 3 which is generally abbreviated as: (1 2 3) Thus, can be used to add one element to the front of an existing linked list. For example, if ''x'' is the list we defined above, then will produce the list: (5 1 2 3) Another useful list procedure is append, which concatenates two existing lists (i.e. combines two lists into a single list).


Trees

Binary tree In computer science, a binary tree is a tree data structure in which each node has at most two children, referred to as the ''left child'' and the ''right child''. That is, it is a ''k''-ary tree with . A recursive definition using set theor ...
s that only store data in their
leaves A leaf (: leaves) is a principal appendage of the stem of a vascular plant, usually borne laterally above ground and specialized for photosynthesis. Leaves are collectively called foliage, as in "autumn foliage", while the leaves, stem, ...
are also easily constructed with . For example, the code: (cons (cons 1 2) (cons 3 4)) results in the tree: ((1 . 2) . (3 . 4)) i.e. * / \ * * / \ / \ 1 2 3 4 Technically, the list (1 2 3) in the previous example is also a binary tree, one which happens to be particularly unbalanced. To see this, simply rearrange the diagram: *--*--*--nil , , , 1 2 3 to the following equivalent: * / \ 1 * / \ 2 * / \ 3 nil


Use in conversation

Cons can refer to the general process of
memory allocation Memory management (also dynamic memory management, dynamic storage allocation, or dynamic memory allocation) is a form of resource management applied to computer memory. The essential requirement of memory management is to provide ways to dynam ...
, as opposed to using destructive operations of the kind that would be used in an imperative programming language. For example:
I sped up the code a bit by putting in
side effect In medicine, a side effect is an effect of the use of a medicinal drug or other treatment, usually adverse but sometimes beneficial, that is unintended. Herbal and traditional medicines also have side effects. A drug or procedure usually use ...
s instead of having it cons ridiculously.


Functional implementation

Since Lisp has
first-class function In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
s, all data structures, including cons cells, can be implemented using functions. For example, in Scheme: (define (cons x y) (lambda (m) (m x y))) (define (car z) (z (lambda (p q) p))) (define (cdr z) (z (lambda (p q) q))) This technique is known as
Church encoding In mathematics, Church encoding is a means of representing data and operators in the lambda calculus. The Church numerals are a representation of the natural numbers using lambda notation. The method is named for Alonzo Church, who first encoded d ...
. It re-implements the ''cons'', ''car'', and ''cdr'' operations, using a function as the "cons cell". Church encoding is a usual way of defining data structures in pure
lambda calculus In mathematical logic, the lambda calculus (also written as ''λ''-calculus) is a formal system for expressing computability, computation based on function Abstraction (computer science), abstraction and function application, application using var ...
, an abstract, theoretical model of computation that is closely related to Scheme. This implementation, while academically interesting, is impractical because it renders cons cells indistinguishable from any other Scheme procedure, as well as introduces unnecessary computational inefficiencies. However, the same kind of encoding can be used for more complex algebraic data types with variants, where it may even turn out to be more efficient than other kinds of encoding. This encoding also has the advantage of being implementable in a statically typed language that doesn't have variants, such as
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, using interfaces instead of lambdas.


See also

*
Lisp (programming language) Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized prefix notation. Originally specified in the late 1950s, it is the second-oldest hig ...
*
CAR and CDR In computer programming, CAR (car) and CDR (cdr) ( or ) are primitive operations on cons cells (or "non-atomic S-expressions") introduced in the Lisp programming language. A cons cell is composed of two pointers; the ''car'' operation extracts ...
*
Constructor (computer science) In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required ...
*
Algebraic data type In computer programming, especially functional programming and type theory, an algebraic data type (ADT) is a kind of composite data type, i.e., a data type formed by combining other types. Two common classes of algebraic types are product ty ...
* Hash consing


References


External links


SDRAW
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
code for drawing draws cons cell structures. From David S. Touretzky. {{Data types Functional programming Lisp (programming language) Articles with example Lisp (programming language) code Articles with example Scheme (programming language) code Composite data types Data types