Next: , Previous: , Up: Lists   [Contents][Index]

#### 5.5.2.5 Association Lists

An association list (or alist) is a list mapping keys to to. Each element of the alist is a cons cell, the car of which is the key, the cdr the value that it associates to. For example an alist could look like,

```((fred . 20)
(bill . 30))
```

this alist has two keys, `fred` and `bill` which both associate to an integer (20 and 30 respectively).

It is possible to make the associated values lists, this looks like,

```((fred 20 male)
(bill 30 male)
(sue  25 female))
```

in this alist the symbol `fred` is associated with the list `(20 male)`.

There are a number of functions which let you interrogate an alist with a given key for its association.

Function: assoc key alist

This function scans the association list alist for the first element whose car is `equal` to key, this element is then returned. If no match of key is found false is returned.

```(assoc 'two '((one . 1) (two . 2) (three . 3)))
⇒ (two . 2)
```
Function: assq key alist

Similar to the function `assoc` except that the function `eq` is used to compare elements instead of `equal`.

It is not usually wise to use `assq` when the keys of the alist may not be symbols—`eq` won’t think two objects are equivalent unless they are the same object!

```(assq "foo" '(("bar" . 1) ("foo" . 2)))
⇒ ()
(assoc "foo" '(("bar" . 1) ("foo" . 2)))
⇒ ("foo" . 2)
```
Function: rassoc association alist

This function searches through alist until it finds an element whose cdr is `equal` to association, that element is then returned. false will be returned if no elements match.

```(rassoc 2 '((one . 1) (two . 2) (three . 3)))
⇒ (two . 2)
```
Function: rassq association alist

This function is equivalent to `rassoc` except that it uses `eq` to make comparisons.

Function: assoc-regexp key-regex alist #!optional fold-case

Same as `assoc`, but it is matched with the regular expression key-regex.

Next: , Previous: , Up: Lists   [Contents][Index]