assq
compares keys with eq?
, assv
uses eqv?
and assoc
uses equal?
. If key
cannot be found in alist (according to whichever equality
predicate is in use), then #f
is returned. These functions
return the entire alist entry found (i.e. both the key and the value).
assq
, assv
and assoc
, except that only the
value associated with key in alist is returned. These
functions are equivalent to
(let ((ent (associator key alist))) (and ent (cdr ent)))
where associator is one of assq
, assv
or assoc
.
These functions do not attempt to verify the structure of alist, and so may cause unusual results if passed an object that is not an association list.
Caution: it is important to remember that the set! and
remove! functions do not always operate as intended. In some
circumstances, the functions will try to modify the first element in the
list; for example, when adding a new entry to an alist,
assoc-set!
conses the new key-value pair on to the beginning of
the alist. However, when this happens, the symbol to which the alist is
bound has not been modified--it still points to the old "beginning"
of the list, which still does not contain the new entry. In order to be
sure that these functions always succeed, even when modifying the
beginning of the alist, you will have to rebind the alist symbol
explicitly to point to the value returned by assoc-set!
, like so:
(set! my-alist (assq-set! my-alist 'sun4 "sparc-sun-solaris"))
Because of this restriction, you may find it more convenient to use hash tables to store dictionary data. If your application will not be modifying the contents of an alist very often, this may not make much difference to you.
Here is a longer example of how alists may be used in practice.
(define capitals '(("New York" . "Albany") ("Oregon" . "Salem") ("Florida" . "Miami"))) ;; What's the capital of Oregon? (assoc "Oregon" capitals) => ("Oregon" . "Salem") (assoc-ref capitals "Oregon") => "Salem" ;; We left out South Dakota. (set! capitals (assoc-set! capitals "South Dakota" "Bismarck")) capitals => (("South Dakota" . "Bismarck") ("New York" . "Albany") ("Oregon" . "Salem") ("Florida" . "Miami")) ;; And we got Florida wrong. (set! capitals (assoc-set! capitals "Florida" "Tallahassee")) capitals => (("South Dakota" . "Bismarck") ("New York" . "Albany") ("Oregon" . "Salem") ("Florida" . "Tallahassee")) ;; After Oregon secedes, we can remove it. (set! capitals (assoc-remove! capitals "Oregon")) capitals => (("South Dakota" . "Bismarck") ("New York" . "Albany") ("Florida" . "Tallahassee"))
Go to the first, previous, next, last section, table of contents.