ZetCode

Scheme association lists

last modified November 24, 2026 Guile 3.0

An association list, or alist, is a list of pairs in which the car of each pair is a key and the cdr its value. The pairs and lists article introduced alists and looked up keys with assq, assv, and assoc. This article builds on that: it adds, changes, and removes entries, both without and with mutation, and uses alists for counting, grouping, and nested configuration data. Alists are simple and keep their order, but a lookup walks the list, so large tables belong in hash tables. The examples run with GNU Guile 3.0.7.

Adding entries

A new entry is added at the front of an alist. Guile's acons takes a key, a value, and an alist, and is a shorthand for (cons (cons key value) alist).

building.scm
(define colours '((red . "#ff0000") (green . "#00ff00")))

(define more (acons 'blue "#0000ff" colours))
(write more)
(newline)
(write colours)
(newline)

(define updated (acons 'red "#cc0000" more))
(write updated)
(newline)
(write (assq 'red updated))
(display " ")
(write (assq 'red more))
(newline)

(define empty '())
(define one (acons 'width 80 empty))
(define two (acons 'height 24 one))
(write two)
(newline)

acons returns a new alist, and colours keeps its two entries; the new list shares them. Adding a key that is already present does not replace the old entry but hides it: the lookup functions return the first match, so updated reports the new red while more still has the old one. This makes adding cheap and lets old versions of the alist live on. An alist can be built from the empty list one entry at a time.

$ guile building.scm
((blue . "#0000ff") (red . "#ff0000") (green . "#00ff00"))
((red . "#ff0000") (green . "#00ff00"))
((red . "#cc0000") (blue . "#0000ff") (red . "#ff0000") (green . "#00ff00"))
(red . "#cc0000") (red . "#ff0000")
((height . 24) (width . 80))

Getting values

assq and its relatives return the whole pair. Guile adds assq-ref, assv-ref, and assoc-ref, which return the value directly, or #f for a missing key. Note that they take the alist first and the key second.

values.scm
(define settings
  '((volume . 7) (muted . #f) (theme . "dark")))

(write (assq-ref settings 'volume))
(display " ")
(write (assq-ref settings 'theme))
(display " ")
(write (assq-ref settings 'language))
(newline)

(write (assq-ref settings 'muted))
(display " ")
(write (assq 'muted settings))
(newline)

(define (setting key default)
  (let ((entry (assq key settings)))
    (if entry (cdr entry) default)))

(write (list (setting 'volume 5) (setting 'language "en")
             (setting 'muted #t)))
(newline)

(define codes '(("SK" . 421) ("HU" . 36) ("AT" . 43)))
(write (assoc-ref codes (string-append "A" "T")))
(newline)

assq-ref returns #f both for the missing language key and for muted, whose value is #f. When #f is a possible value, assq tells the two cases apart, because it returns the pair. The setting procedure builds on that and returns a default for missing keys only, so the stored #f of muted wins over the default #t. String keys need assoc-ref, which compares with equal?.

$ guile values.scm
7 "dark" #f
#f (muted . #f)
(7 "en" #f)
43

Keys and values

An alist is an ordinary list, so the procedures from the higher-order procedures article work on it directly. Each element passed to the procedure is one key and value pair.

entries.scm
(define stock
  '((apples . 25) (pears . 0) (plums . 40) (cherries . 3)))

(write (map car stock))
(newline)
(write (map cdr stock))
(newline)

(for-each (lambda (entry)
            (display (car entry))
            (display ": ")
            (display (cdr entry))
            (newline))
          stock)

(write (filter (lambda (entry) (< (cdr entry) 5)) stock))
(newline)
(display (apply + (map cdr stock)))
(newline)
(write (map (lambda (entry) (cons (car entry) (* 2 (cdr entry))))
            stock))
(newline)

Mapping car over the alist returns the keys and mapping cdr the values. for-each prints the entries, filter keeps those with a low stock, and the sum of the values gives the total count. The last map returns a new alist with the same keys and doubled values.

$ guile entries.scm
(apples pears plums cherries)
(25 0 40 3)
apples: 25
pears: 0
plums: 40
cherries: 3
((pears . 0) (cherries . 3))
68
((apples . 50) (pears . 0) (plums . 80) (cherries . 6))

Updating without mutation

To change a value without modifying the existing alist, remove the old entry and add a new one. The SRFI 1 list library provides alist-delete, which removes all entries with a key, and alist-cons, the standard name for acons.

update.scm
(use-modules (srfi srfi-1))

(define (alist-set alist key value)
  (alist-cons key value (alist-delete key alist eq?)))

(define (alist-change alist key f)
  (map (lambda (entry)
         (if (eq? (car entry) key)
             (cons key (f (cdr entry)))
             entry))
       alist))

(define prices '((bread . 2) (milk . 1) (cheese . 6)))

(define p2 (alist-set prices 'milk 2))
(define p3 (alist-set p2 'butter 3))
(define p4 (alist-change p3 'cheese (lambda (x) (* x 2))))

(write prices)
(newline)
(write p2)
(newline)
(write p3)
(newline)
(write p4)
(newline)
(write (alist-delete 'bread p4))
(newline)

alist-set replaces the value of a key, or adds the key if it is missing. alist-delete takes the equality procedure as an optional third argument and uses equal? without it. The updated entry moves to the front. alist-change keeps the order: it maps over the entries and applies f to the value of the matching one. prices is printed first and is unchanged; every step produced a new alist.

$ guile update.scm
((bread . 2) (milk . 1) (cheese . 6))
((milk . 2) (bread . 2) (cheese . 6))
((butter . 3) (milk . 2) (bread . 2) (cheese . 6))
((butter . 3) (milk . 2) (bread . 2) (cheese . 12))
((butter . 3) (milk . 2) (cheese . 12))

Updating in place

Guile's assq-set!, assv-set!, and assoc-set! change an alist in place and return it. assq-remove! and its relatives delete an entry. Mutation must not be applied to literal constants, so the alist is first copied with SRFI 1's alist-copy.

mutating.scm
(use-modules (srfi srfi-1))

(define inventory (alist-copy '((nails . 500) (screws . 200))))

(assq-set! inventory 'nails 450)
(write inventory)
(newline)

(write (assq-set! inventory 'bolts 80))
(newline)
(write inventory)
(newline)

(set! inventory (assq-set! inventory 'bolts 80))
(write inventory)
(newline)

(set! inventory (assq-remove! inventory 'screws))
(write inventory)
(newline)
(set! inventory (assq-remove! inventory 'bolts))
(write inventory)
(newline)

When the key exists, assq-set! replaces the value inside the existing pair, and inventory shows the new count of nails. When the key is missing, it adds a new pair at the front and returns the longer list, but inventory still points to the old first pair and does not see the bolts. The result must therefore always be stored back with set!. The same holds for assq-remove!, which may return a different first pair.

$ guile mutating.scm
((nails . 450) (screws . 200))
((bolts . 80) (nails . 450) (screws . 200))
((nails . 450) (screws . 200))
((bolts . 80) (nails . 450) (screws . 200))
((bolts . 80) (nails . 450))
((nails . 450))

Counting

An alist is a natural place for counts. The program counts the words of a text given as a list of symbols, with acons for new words and set-cdr! to increase existing counts.

counting.scm
(define (count-words words)
  (let loop ((words words) (counts '()))
    (if (null? words)
        (reverse counts)
        (let* ((word (car words))
               (entry (assq word counts)))
          (if entry
              (begin
                (set-cdr! entry (+ (cdr entry) 1))
                (loop (cdr words) counts))
              (loop (cdr words) (acons word 1 counts)))))))

(define text
  '(the cat saw the dog and the dog saw the cat run))

(define counts (count-words text))
(write counts)
(newline)

(define (most-frequent counts)
  (let loop ((rest (cdr counts)) (best (car counts)))
    (cond ((null? rest) best)
          ((> (cdar rest) (cdr best)) (loop (cdr rest) (car rest)))
          (else (loop (cdr rest) best)))))

(write (most-frequent counts))
(newline)

The loop keeps the counts found so far. For a known word, it increments the count in the found pair with set-cdr!; the pairs were created by acons in the loop, so they may be modified. New words are added at the front, and the final reverse lists them in the order of first appearance. most-frequent walks the counts and keeps the pair with the highest value; cdar is the count of the first remaining entry.

$ guile counting.scm
((the . 4) (cat . 2) (saw . 2) (dog . 2) (and . 1) (run . 1))
(the . 4)

Grouping

Grouping collects the items that share a key. The value of each entry is a list, and every item is added to the list of its key. The data are pairs of a name and a city.

grouping.scm
(define people
  '(("Lucia" . bratislava) ("Tomas" . kosice) ("Eva" . bratislava)
    ("Peter" . zilina) ("Jana" . kosice) ("Marek" . bratislava)))

(define (group-by-city people)
  (let loop ((rest people) (groups '()))
    (if (null? rest)
        (reverse groups)
        (let* ((name (caar rest))
               (city (cdar rest))
               (group (assq city groups)))
          (if group
              (begin
                (set-cdr! group (append (cdr group) (list name)))
                (loop (cdr rest) groups))
              (loop (cdr rest) (acons city (list name) groups)))))))

(define groups (group-by-city people))

(for-each (lambda (group)
            (display (car group))
            (display ": ")
            (write (cdr group))
            (newline))
          groups)

(write (map (lambda (g) (cons (car g) (length (cdr g)))) groups))
(newline)

caar and cdar extract the name and the city of the first person. If the city already has a group, the name is appended to its list, which keeps the names in their original order. Otherwise a new group with a one-element list is added. The second output turns the groups into an alist of group sizes.

$ guile grouping.scm
bratislava: ("Lucia" "Eva" "Marek")
kosice: ("Tomas" "Jana")
zilina: ("Peter")
((bratislava . 3) (kosice . 2) (zilina . 1))

Nested alists

The value in an alist may be another alist, which gives tree-shaped data such as configuration files. A lookup then follows a path of keys from the outer level inwards.

nested.scm
(define config
  '((server . ((host . "localhost") (port . 8080)))
    (database . ((name . "shop")
                 (pool . ((min . 2) (max . 10)))))
    (debug . #t)))

(define (get-in alist path)
  (cond ((null? path) alist)
        ((not (pair? alist)) #f)
        (else
         (let ((entry (assq (car path) alist)))
           (and entry (get-in (cdr entry) (cdr path)))))))

(write (get-in config '(server port)))
(newline)
(write (get-in config '(database pool max)))
(newline)
(write (get-in config '(database pool)))
(newline)
(write (get-in config '(debug)))
(newline)
(write (get-in config '(server user)))
(newline)
(write (get-in config '(debug level)))
(newline)

get-in looks up the first key of the path and continues with the rest of the path in the found value. An empty path returns the current value, which may be a whole subtree, as for (database pool). A missing key returns #f through the and, and the pair? test stops a path that goes deeper than the data, as with (debug level), where the value #t is not an alist.

$ guile nested.scm
8080
10
((min . 2) (max . 10))
#t
#f
#f

Comparing keys

The choice between assq, assv, and assoc depends on the key type, as described in the booleans and equality article. Guile's built-in assoc takes only two arguments; SRFI 1 replaces it with a version that accepts any comparison procedure as the third argument.

comparing.scm
(use-modules (srfi srfi-1))

(define points
  (list (cons (list 0 0) "origin")
        (cons (list 1 0) "east")
        (cons (list 0 1) "north")))

(write (assoc (list 1 0) points))
(display " ")
(write (assq (list 1 0) points))
(newline)

(define sizes '((1 . "small") (2 . "medium") (3 . "large")))

(write (assoc 2.0 sizes))
(display " ")
(write (assoc 2.0 sizes =))
(newline)

(define grades '((90 . "A") (80 . "B") (70 . "C") (60 . "D")))

(define (grade score)
  (let ((entry (assoc score grades >=)))
    (if entry (cdr entry) "F")))

(write (map grade '(95 83 70 61 42)))
(newline)

The keys of points are lists built at run time. assoc finds (1 0) by structure, while assq compares identity and fails. equal? does not consider the inexact 2.0 equal to the exact key 2, but numeric = does. The comparison is called with the search key first and the entry key second, so (assoc score grades >=) finds the first threshold that the score reaches. The grade table relies on the order of the entries, from the highest threshold down.

$ guile comparing.scm
((1 0) . "east") #f
#f (2 . "medium")
("A" "B" "C" "D" "F")

Source

Association Lists — GNU Guile Reference Manual

SRFI 1: Association lists

In this article we have added entries with acons, read values with assq-ref and with defaults, walked keys and values, updated alists with alist-delete and in place with assq-set!, counted and grouped data, followed paths through nested alists, and chosen how keys are compared. The pairs and lists article covers the basic lookup procedures, and the closures article uses an alist as a memoization cache.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.