Next: , Up: Sequences   [Contents][Index]

#### 5.5.1 Cons Cells

A cons cell is an ordered pair of two objects, the car and the cdr.

The read syntax of a cons cell is an opening parenthesis followed by the read syntax of the car, a dot, the read syntax of the cdr and a closing parenthesis. For example a cons cell with a car of 10 and a cdr of the string ‘foo’ would be written as,

```(10 . "foo")
```
Function: cons car cdr

This function creates a new cons cell. It will have a car of car and a cdr of cdr.

```(cons 10 "foo")
⇒ (10 . "foo")
```
Function: consp object

This function returns true if object is a cons cell.

```(consp '(1 . 2))
⇒ t

(consp '())
⇒ ()

(consp (cons 1 2))
⇒ t
```

The strange syntax ‘'(1 . 2)’ is known as quoting (see Quoting), it tells the evaluator that the object following the quote-mark is a constant, and therefore should not be evaluated. This will be explained in more detail later.

In Lisp an atom is any object which is not a cons cell (and is, therefore, atomic).

Function: atom object

Returns true if object is an atom (not a cons cell).

Given a cons cell there are a number of operations which can be performed on it.

Function: car cons-cell

This function returns the object which is the car (first element) of the cons cell cons-cell.

```(car (cons 1 2))
⇒ 1

(car '(1 . 2))
⇒ 1
```
Function: cdr cons-cell

This function returns the cdr (second element) of the cons cell cons-cell.

```(cdr (cons 1 2))
⇒ 2

(cdr '(1 . 2))
⇒ 2
```

Rep also provides `cXXr`, `cXXXr`, and `cXXXXr`, where each x is either `a` or `d`. For example, `(cadr z)` is equal to `(car (cdr z))`.

Function: rplaca cons-cell new-car

This function sets the value of the car (first element) in the cons cell cons-cell to new-car. The value returned is cons-cell.

```(setq x (cons 1 2))
⇒ (1 . 2)
(rplaca x 3)
⇒ (3 . 2)
x
⇒ (3 . 2)
```
Function: rplacd cons-cell new-cdr

This function is similar to `rplacd` except that the cdr slot (second element) of cons-cell is modified.

Function: setcar cons-cell new-car
Function: setcdr cons-cell new-cdr

Same as `rplaca` and `rplacd` respectively, but the return value is new-car / new-cdr.

Next: , Up: Sequences   [Contents][Index]