An “association list” (or “alist”) is a list of pairs. The car of each pair contains a key value, and the cdr contains the associated data value. They can be used to construct simple look–up tables in Scheme. Note that association lists are probably inappropriate for performance–critical use on large data; in these cases, hash tables or some other alternative should be employed.
R5RS+ alist must be an association list: a list of pairs.
These procedures find the first pair in alist whose car field is
key, and returns that pair. If no pair in alist has
key as its car, then
#f is returned.
eq? to compare key with the car fields of
the pairs in alist, while
(define e '((a 1) (b 2) (c 3))) (assq 'a e) => (a 1) (assq 'b e) => (b 2) (assq 'd e) => #f (assq (list 'a) '(((a)) ((b)) ((c)))) => #f (assoc (list 'a) '(((a)) ((b)) ((c)))) => ((a)) (assq 5 '((2 3) (5 7) (11 13))) => *unspecified* (assv 5 '((2 3) (5 7) (11 13))) => (5 7)
assoc is extended from its R5RS definition to allow the
client to pass in an optional equality procedure = used to compare
The comparison procedure is used to compare the elements ei of list to the key parameter in this way:
(= key (car ei)) ; list is (E1 ... En)
that is, the first argument is always key, and the second argument
is one of the list elements. Thus one can reliably find the first entry
of alist whose key is greater than five with
Note that fully general alist searching may be performed with the
;; Look up the first association in alist with an even key: (find (lambda (a) (even? (car a))) alist)
(lambda (key datum alist) (cons (cons key datum) alist))
Cons a new alist entry mapping key to datum onto alist.
Make a fresh copy of alist. This means copying each pair that forms an association as well as the spine of the list:
(lambda (a) (map (lambda (elt) (cons (car elt) (cdr elt))) a))
Delete all associations from alist with the given key, using
the key-comparison procedure =, which defaults to
The dynamic order in which the various applications of = are made
is not specified.
Return values may share common tails with the alist argument. The alist is not disordered: elements that appear in the result alist occur in the same order as they occur in alist.
The comparison procedure is used to compare the element keys ki of
alist’s entries to the key parameter in this way:
ki). Thus, one can reliably remove all entries of alist whose
key is greater than five with
(alist-delete 5 alist <).
alist-delete! is the linear–update variant of
alist-delete; it is allowed, but not required, to alter cons
cells from the alist parameter to construct the result.