# Cons

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Cons
> Markdown URL: https://mediated.wiki/source/Cons.md
> Source: https://en.wikipedia.org/wiki/Cons
> Source revision: 1333504977
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{short description|Function and primitive data structure in Lisp and other functional programming languages}}
{{about|the Lisp programming function}}
{{more citations needed|date=January 2019}}
{{lowercase title}}
In [computer programming](/source/computer_programming), '''{{lisp2|cons}}''' ({{IPAc-en|ˈ|k|ɒ|n|z}} or {{IPAc-en|ˈ|k|ɒ|n|s}}) is a fundamental [function](/source/subroutine) in most dialects of the [Lisp](/source/Lisp_(programming_language)) programming language. {{lisp2|cons}} ''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](/source/s-expressions) ("NATSes"), or (cons) [pairs](/source/ordered_pair). In Lisp jargon, the expression "to cons ''x'' onto ''y''" means to construct a new object with <code>(cons ''x'' ''y'')</code>. The resulting pair has a left half, referred to as the {{lisp2|car}} (the first element, or ''['''c'''ontents of the '''a'''ddress part of '''r'''egister](/source/CAR_and_CDR)''), and a right half, referred to as the {{lisp2|cdr}} (the second element, or ''['''c'''ontents of the '''d'''ecrement part of '''r'''egister](/source/CAR_and_CDR)'').

It is loosely related to the [object-oriented](/source/object-oriented_programming) notion of a [constructor](/source/constructor_(computer_science)), which creates a new object given arguments, and more closely related to the constructor function of an [algebraic data type](/source/algebraic_data_type) system.

The word "cons" and expressions like "to cons onto" are also part of a more general [functional programming](/source/functional_programming) jargon. Sometimes [operators](/source/Operator_(programming)) that have a similar purpose, especially in the context of list processing, are pronounced "cons". (A good example is the <code>::</code> operator in [ML](/source/ML_programming_language), [Scala](/source/Scala_(programming_language)), [F#](/source/F_Sharp_(programming_language)), [Lean](/source/Lean_(proof_assistant)), [Rocq](/source/Rocq), and [Elm](/source/Elm_(programming_language)) or the <code>:</code> operator in [Haskell](/source/Haskell_(programming_language)), which adds an element to the beginning of a list.)

==Use==
Although cons cells can be used to hold [ordered pair](/source/ordered_pair)s of data, they are more commonly used to construct more complex compound data structures, notably [lists](/source/Linked_list) and [binary tree](/source/binary_tree)s.

===Ordered pairs===
For example, the Lisp expression {{lisp2|(cons 1 2)}} constructs a cell holding 1 in its left half (the so-called {{lisp2|car}} field) and 2 in its right half (the {{lisp2|cdr}} field). In Lisp notation, the value {{lisp2|(cons 1 2)}} 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===
thumb|left|350px|Cons cell diagram for the list (42 69 613), written with <code>cons</code>: <syntaxhighlight lang="lisp">(cons 42 (cons 69 (cons 613 nil)))</syntaxhighlight> and written with <code>list</code>: <syntaxhighlight lang="lisp">(list 42 69 613)</syntaxhighlight>
{{clear}}
In Lisp, lists are implemented on top of cons pairs. More specifically, any list structure in Lisp is either:

#An empty list {{lisp2|()}}, which is a special object usually called {{lisp2|nil}}.
#A cons cell whose {{lisp2|car}} is the first element of the list and whose {{lisp2|cdr}} is a [list](/source/list) containing the rest of the elements.
This forms the basis of a simple, [singly linked list](/source/Linked_list) structure whose contents can be manipulated with {{lisp2|cons}}, {{lisp2|car}}, and {{lisp2|cdr}}. Note that {{lisp2|nil}} 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 {{lisp2|nil}}, the empty list
#Cons 2 onto the result
#Cons 1 onto the result

which is equivalent to the single expression:

 <syntaxhighlight lang="lisp">(cons 1 (cons 2 (cons 3 nil)))</syntaxhighlight>

or its shorthand:

 <syntaxhighlight lang="lisp">(list 1 2 3)</syntaxhighlight>

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, {{lisp2|cons}} 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 {{lisp2|(cons 5 x)}} will produce the list:

 (5 1 2 3)

Another useful list procedure is [append](/source/Append), which [concatenates](/source/Concatenation) two existing lists (i.e. combines two lists into a single list).

===Trees===
[Binary tree](/source/Binary_tree)s that only store data in their [leaves](/source/Leaf_node) are also easily constructed with {{lisp2|cons}}. For example, the code:

 <syntaxhighlight lang="lisp">(cons (cons 1 2) (cons 3 4))</syntaxhighlight>

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](/source/Dynamic_memory_allocation), as opposed to using destructive operations of the kind that would be used in an imperative programming language.{{citation needed|date=October 2022}} For example:

<blockquote>I sped up the code a bit by putting in [side effect](/source/side_effect_(computer_science))s instead of having it cons ridiculously.</blockquote>

==Functional implementation==
Since Lisp has [first-class function](/source/first-class_function)s, all data structures, including cons cells, can be implemented using functions. For example, in [Scheme](/source/Scheme_(programming_language)):
<syntaxhighlight lang="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)))
</syntaxhighlight>
This technique is known as [Church encoding](/source/Church_encoding). 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](/source/lambda_calculus), 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.<ref>{{cite web |url=http://www.st.cs.ru.nl/papers/2006/janj2006-TFP06-EfficientInterpretation.pdf |title=Efficient Interpretation by Transforming Data Types and Patterns to Functions |accessdate=2009-03-01 |url-status=dead |archiveurl=https://web.archive.org/web/20100331083602/http://www.st.cs.ru.nl/papers/2006/janj2006-TFP06-EfficientInterpretation.pdf |archivedate=2010-03-31 }}</ref>
This encoding also has the advantage of being implementable in a statically typed language that doesn't have variants, such as [Java](/source/Java_(programming_language)), using interfaces instead of lambdas.

==See also==
* [Lisp (programming language)](/source/Lisp_(programming_language))
* [CAR and CDR](/source/CAR_and_CDR)
* [Constructor (computer science)](/source/Constructor_(computer_science))
* [Algebraic data type](/source/Algebraic_data_type)
* [Hash consing](/source/Hash_consing)

==References==
<references/>

==External links==
* [https://www.cs.cmu.edu/~dst/Lisp/sdraw/ SDRAW], [Common Lisp](/source/Common_Lisp)  code for drawing draws cons cell structures. From David S. Touretzky.

{{Data types}}

Category:Functional programming
Category:Lisp (programming language)
Category:Articles with example Lisp (programming language) code
Category:Articles with example Scheme (programming language) code
Category:Composite data types
Category:Data types

---
Adapted from the Wikipedia article [Cons](https://en.wikipedia.org/wiki/Cons) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Cons?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
