|
Practical Common LispCL-USER> (assoc 'a '((a . 1) (b . 2) (c . 3))) (A . 1) CL-USER> (assoc 'c '((a . 1) (b . 2) (c . 3))) (C . 3) CL-USER> (assoc 'd '((a . 1) (b . 2) (c . 3))) NIL To get the value corresponding to a given key, you simply pass the result of ASSOC to CDR. CL-USER> (cdr (assoc 'a '((a . 1) (b . 2) (c . 3)))) 1 By default the key given is compared to the keys in the alist using EQL, but you can change that with the standard combination of :key and :test keyword arguments. For instance, if you wanted to use string keys, you might write this: CL-USER> (assoc "a" '(("a" . 1) ("b" . 2) ("c" . 3)) :test #'string=) ("a" . 1) Without specifying :test to be STRING=, that ASSOC would probably return NIL because two strings with the same contents aren't necessarily EQL. CL-USER> (assoc "a" '(("a" . 1) ("b" . 2) ("c" . 3))) NIL Because ASSOC searches the list by scanning from the front of the list, one key/value pair in an alist can shadow other pairs with the same key later in the list. CL-USER> (assoc 'a '((a . 10) (a . 1) (b . 2) (c . 3))) (A . 10) You can add a pair to the front of an alist with CONS like this: (cons (cons 'new-key 'new-value) alist) However, as a convenience, Common Lisp provides the function ACONS, which lets you write this: (acons 'new-key 'new-value alist) Like CONS, ACONS is a function and thus can't modify the place holding the alist it's passed ...» |
Код для вставки книги в блог HTML
phpBB
текст
|
|