Next: Association Lists, Up: Lists in Elisp [Index]
Also by convention, the CDR of the last cons cell in a list is ‘nil’. We call such a ‘nil’-terminated structure a “proper list”. In Emacs Lisp, the symbol ‘nil’ is both a symbol and a list with no elements. For convenience, the symbol ‘nil’ is considered to have ‘nil’ as its CDR (and also as its CAR).
Hence, the CDR of a proper list is always a proper list. The CDR of a nonempty proper list is a proper list containing all the elements except the first.
If the CDR of a list’s last cons cell is some value other than ‘nil’, we call the structure a “dotted list”, since its printed representation would use dotted pair notation
Because most cons cells are used as part of lists, we refer to any structure made out of cons cells as a “list structure”.
The read syntax and printed representation for lists are identical, and consist of a left parenthesis, an arbitrary number of elements, and a right parenthesis.
(a b c) () or nil ((a b c) (d e f))
Upon reading, each object inside the parentheses becomes an element of the list. That is, a cons cell is made for each element. The CAR slot of the cons cell holds the element, and its CDR slot refers to the next cons cell of the list, which holds the next element in the list. The CDR slot of the last cons cell is set to hold ‘nil’.
Dotted pair notation is a general syntax for cons cells that represents the CAR and CDR explicitly.
In this syntax, ‘(A . B)’ stands for a cons cell whose CAR is the object A and whose CDR is the object B. In dotted pair notation, the list ‘(1 2 3)’ is written as (‘1 . (2 . (3 . nil)))’.
Dotted pair notation is more general than list syntax because the CDR does not have to be a list. However, it is more cumbersome in cases where list syntax would work. For ‘nil’-terminated lists, you can use either notation, but list notation is usually clearer and more convenient. When printing a list, the dotted pair notation is only used if the CDR of a cons cell is not a list.
You can combine dotted pair notation with list notation to represent conveniently a chain of cons cells with a non-‘nil’ final CDR. You write a dot after the last element of the list, followed by the CDR of the final cons cell. For example, ‘(rose violet . buttercup)’ is equivalent to ‘(rose . (violet . buttercup))’. The list ‘(rose violet)’ is equivalent to ‘(rose . (violet))’. Similarly, the three-element list ‘(rose violet buttercup)’ is equivalent to ‘(rose . (violet . (buttercup)))’.
Next: Association Lists, Up: Lists in Elisp [Index]