Next: , Up: Sequence Functions   [Index]


E.3.1 Building Cons Cells and Lists

Lists reside at the very heart of Lisp. ‘cons’ is the fundamental list-building function.

Function: cons object1 object2

This function is the most basic function for building new list structure. It creates a new cons cell, making OBJECT1 the CAR, and OBJECT2 the CDR. It then returns the new cons cell.

The arguments OBJECT1 and OBJECT2 may be any Lisp objects, but most often OBJECT2 is a list.

‘cons’ is often used to add a single element to the front of a list. This is called “consing the element onto the list”.

Function: list &rest objects

This function creates a list with OBJECTS as its elements (or ‘nil’ if no objects are given). The resulting list is always ‘nil’-terminated.

Function: make-list length object

This function creates a list of LENGTH elements, in which each element is OBJECT.

Function: append &rest sequences

This function returns a list containing all the elements of SEQUENCES. The SEQUENCES may be lists, vectors, bool-vectors, or strings, but the last one should usually be a list. All arguments except the last one are copied, so none of the arguments is altered.

The final argument to ‘append’ may be any Lisp object. The final argument is not copied or converted; it becomes the CDR of the last cons cell in the new list.

See ‘nconc’ in *note Rearrangement::, for a way to join lists with no copying.

An empty sequence contributes nothing to the value returned by ‘append’. As a consequence of this, a final ‘nil’ argument forces a copy of the previous argument. This once was the usual way to copy a list, before the function ‘copy-sequence’ was invented.

With the help of ‘apply’, we can append all the lists in a list of lists:

(apply 'append '((a b c) nil (x y z) nil))
⇒ (a b c x y z)
Function: copy-tree &optional vecp

This function returns a copy of the tree TREE. If TREE is a cons cell, this makes a new cons cell with the same CAR and CDR, then recursively copies the CAR and CDR in the same way.

if VECP is non-‘nil’, it copies vectors too (and operates recursively on their elements.

Function: flatten-tree tree

This function returns a “flattened” copy of TREE, that is, a list containing all the non-‘nil’ terminal nodes, or leaves, of the tree of cons cells rooted at TREE.

Function: number-sequence from &optional to separation

This function returns a list of numbers starting with FROM and incrementing by SEPARATION, and ending at or just before TO. SEPARATION can be positive or negative and defaults to 1.

All arguments are numbers. Floating-point arguments can be tricky.

The Nth element of the list is computed by the exact formula ‘(+ FROM (* N SEPARATION))’. Thus, if one wants to make sure that TO is included in the list, one can pass an expression of this exact type for TO.


Next: Sequence Predicate Functions, Up: Sequence Functions   [Index]