Skip to content

Alist Example

The following example shows how alists may be used in practice.

emacs-lisp
(define capitals (list (cons "New York" "Albany")
                       (cons "Oregon"   "Salem")
                       (cons "Florida"  "Miami")))

Other ways to create an alist are

emacs-lisp
(define capitals (acons "New York" "Albany"
                        (acons "Oregon" "Salem"
                               (acons "Florida"  "Miami" '()))))

or

emacs-lisp
(use-modules (srfi srfi-1)) ; for alist-copy
(define capitals (alist-copy
                   '(("New York" . "Albany")
                     ("Oregon"   . "Salem")
                     ("Florida"  . "Miami"))))

Here alist-copy is necessary if we intend to modify the alist, because a literal like '(("New York" . "Albany") ...) cannot be modified.

We can now operate on the alist.

emacs-lisp
;; 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" "Pierre"))
capitals
⇒ (("South Dakota" . "Pierre")
    ("New York" . "Albany")
    ("Oregon" . "Salem")
    ("Florida" . "Miami"))

;; And we got Florida wrong.
(set! capitals
      (assoc-set! capitals "Florida" "Tallahassee"))
capitals
⇒ (("South Dakota" . "Pierre")
    ("New York" . "Albany")
    ("Oregon" . "Salem")
    ("Florida" . "Tallahassee"))

;; After Oregon secedes, we can remove it.
(set! capitals
      (assoc-remove! capitals "Oregon"))
capitals
⇒ (("South Dakota" . "Pierre")
    ("New York" . "Albany")
    ("Florida" . "Tallahassee"))