lispconsland-of-lisp

Memory allocation in Lisp


> (cons 2 3) 
(2 . 3)

The Lisp environment needs to allocate only a single cons cell to connect the two items.

Above is from the Lisp book "Land of Lisp". I don't understand why this pair is only located in a single cons cell. What does the memory look like for this data?


Solution

  • A cons cell always holds two values, called car and cdr:

    +-----+-----+
    | car | cdr |
    +-----+-----+
    

    To represent a cons cell, Lisp has the "dot notation":

    (car . cdr)
    

    The function cons creates such a cons cell from its two arguments:

    (cons 1 2)
    => (1 . 2)
    

    which can be thought of like this:

    +-----+-----+
    |  1  |  2  |
    +-----+-----+
    

    The values of a cons cell can also be "references" or "pointers" to other things. Those other things can, for example, be other cons cells:

    +-----+-----+     +-----+-----+
    |  1  |   ------->|  2  | nil |
    +-----+-----+     +-----+-----+
    

    This would be (1 . (2 . nil)) in dot notation. This chaining is used in Lisp to represent lists. Since lists are used for the representation of code, they are important for Lisp. Therefore, there is a shorter notation for them: (1 2).