[ < ] [ > ]   [ << ] [Plus haut] [ >> ]         [Top] [Table des matières] [Index] [ ? ]

5.1 Lists and Cons Cells

Lists in Lisp are not a primitive data type; they are built up from cons cells. A cons cell is a data object that represents an ordered pair. That is, it has two slots, and each slot holds, or refers to, some Lisp object. One slot is known as the CAR, and the other is known as the CDR. (These names are traditional; see Cons Cell and List Types.) CDR is pronounced “could-er.”

We say that “the CAR of this cons cell is” whatever object its CAR slot currently holds, and likewise for the CDR.

A list is a series of cons cells “chained together,” so that each cell refers to the next one. There is one cons cell for each element of the list. By convention, the CARs of the cons cells hold the elements of the list, and the CDRs are used to chain the list: the CDR slot of each cons cell refers to the following cons cell. The CDR of the last cons cell is nil. This asymmetry between the CAR and the CDR is entirely a matter of convention; at the level of cons cells, the CAR and CDR slots have the same characteristics.

Since nil is the conventional value to put in the CDR of the last cons cell in the list, we call that case a true list.

In Lisp, we consider the symbol nil a list as well as a symbol; it is the list with no elements. For convenience, the symbol nil is considered to have nil as its CDR (and also as its CAR). Therefore, the CDR of a true list is always a true list.

If the CDR of a list's last cons cell is some other value, neither nil nor another cons cell, we call the structure a dotted list, since its printed representation would use ‘.’. There is one other possibility: some cons cell's CDR could point to one of the previous cons cells in the list. We call that structure a circular list.

For some purposes, it does not matter whether a list is true, circular or dotted. If the program doesn't look far enough down the list to see the CDR of the final cons cell, it won't care. However, some functions that operate on lists demand true lists and signal errors if given a dotted list. Most functions that try to find the end of a list enter infinite loops if given a circular list.

Because most cons cells are used as part of lists, the phrase list structure has come to mean any structure made out of cons cells.

The CDR of any nonempty true list l is a list containing all the elements of l except the first.

Voir la section Cons Cell and List Types, for the read and print syntax of cons cells and lists, and for “box and arrow” illustrations of lists.


[ < ] [ > ]   [ << ] [Plus haut] [ >> ]         [Top] [Table des matières] [Index] [ ? ]

Ce document a été généré par Eric Reinbold le 13 Octobre 2007 en utilisant texi2html 1.78.