ZetCode

Scheme hash tables

last modified November 24, 2026 Guile 3.0

A hash table maps keys to values. It computes a hash number from each key and uses it to find the entry directly, so a lookup takes about the same time whether the table holds ten entries or a million. An association list must be searched from the start, which is fine for small tables but slow for large ones. This article uses Guile's built-in hash tables first and then the portable SRFI 69 interface. The examples run with GNU Guile 3.0.7.

Creating a hash table

make-hash-table creates an empty table, hash-set! stores a value under a key, and hash-ref retrieves it. The table grows as needed.

creating.scm
(define capitals (make-hash-table))

(hash-set! capitals "Slovakia" "Bratislava")
(hash-set! capitals "Hungary" "Budapest")
(hash-set! capitals "Poland" "Warsaw")

(write (hash-ref capitals "Hungary"))
(newline)
(write (hash-ref capitals "Austria"))
(newline)
(write (hash-ref capitals "Austria" "unknown"))
(newline)
(write (hash-count (const #t) capitals))
(newline)
(write (hash-table? capitals))
(newline)

hash-ref returns #f for a missing key, or the default given as its third argument. Guile has no procedure that returns the number of entries directly; hash-count counts the entries that satisfy a predicate, and (const #t), a procedure that always returns true, counts them all. hash-table? tests for a hash table.

$ guile creating.scm
"Budapest"
#f
"unknown"
3
#t

Updating and removing entries

Setting an existing key replaces its value. hash-remove! deletes an entry, and hash-clear! empties the whole table.

updating.scm
(define stock (make-hash-table))

(hash-set! stock 'apples 40)
(hash-set! stock 'pears 12)
(hash-set! stock 'plums 0)

(hash-set! stock 'apples 35)
(write (hash-ref stock 'apples))
(newline)

(define (add-stock! item amount)
  (hash-set! stock item (+ (hash-ref stock item 0) amount)))

(add-stock! 'pears 8)
(add-stock! 'cherries 50)
(write (list (hash-ref stock 'pears) (hash-ref stock 'cherries)))
(newline)

(hash-remove! stock 'plums)
(write (hash-ref stock 'plums 'gone))
(newline)
(write (hash-count (const #t) stock))
(newline)
(write (hash-count (lambda (key value) (> value 20)) stock))
(newline)

(hash-clear! stock)
(write (hash-count (const #t) stock))
(newline)

The second hash-set! for apples overwrites the first. add-stock! reads the current amount with a default of 0 and stores the sum, which works for both existing and new items. After the plums are removed, the table holds three items, and the predicate passed to hash-count receives the key and the value, so it can count the items with more than 20 pieces.

$ guile updating.scm
35
(20 50)
gone
3
2
0

Iterating over a table

hash-for-each calls a procedure with each key and value, hash-map->list collects the results of such calls in a list, and hash-fold combines the entries into a single value. The entries come in an order determined by the hash numbers, not in the order of insertion.

iterating.scm
(define ages (make-hash-table))

(hash-set! ages 'eva 34)
(hash-set! ages 'peter 27)
(hash-set! ages 'tomas 41)

(hash-for-each
 (lambda (name age)
   (display name)
   (display " is ")
   (display age)
   (newline))
 ages)

(write (hash-map->list cons ages))
(newline)
(write (hash-map->list (lambda (name age) name) ages))
(newline)

(write (hash-fold (lambda (name age total) (+ age total)) 0 ages))
(newline)
(write (hash-fold (lambda (name age oldest)
                    (if (or (not oldest) (> age (hash-ref ages oldest)))
                        name
                        oldest))
                  #f
                  ages))
(newline)

The names are printed in an order that differs from the order of the hash-set! calls. hash-map->list with cons turns the table into an association list. hash-fold takes a procedure of the key, the value, and the accumulated result, the initial value, and the table; the first fold sums the ages, and the second keeps the name of the oldest person, starting with #f.

$ guile iterating.scm
peter is 27
eva is 34
tomas is 41
((tomas . 41) (eva . 34) (peter . 27))
(tomas eva peter)
102
tomas

Handles

Because hash-ref returns #f for a missing key, it cannot tell a missing key from a key whose value is #f. hash-get-handle returns the entry itself, a pair of the key and the value, or #f when the key is absent.

handles.scm
(define options (make-hash-table))

(hash-set! options 'verbose #f)
(hash-set! options 'colour #t)

(write (list (hash-ref options 'verbose) (hash-ref options 'quiet)))
(newline)
(write (hash-get-handle options 'verbose))
(newline)
(write (hash-get-handle options 'quiet))
(newline)

(define (option-status name)
  (let ((handle (hash-get-handle options name)))
    (cond ((not handle) "not set")
          ((cdr handle) "on")
          (else "off"))))

(for-each (lambda (name)
            (display name)
            (display ": ")
            (display (option-status name))
            (newline))
          (list 'verbose 'colour 'quiet))

(define handle (hash-create-handle! options 'level 1))
(set-cdr! handle 3)
(write (hash-ref options 'level))
(newline)

verbose is stored with the value #f, and quiet is not stored at all, yet hash-ref returns #f for both. Their handles differ: the pair (verbose . #f) and #f. option-status uses the handle to report three states. hash-create-handle! returns the handle of a key, adding the key with an initial value if needed, and changing the cdr of the handle changes the value in the table.

$ guile handles.scm
(#f #f)
(verbose . #f)
#f
verbose: off
colour: on
quiet: not set
3

Key equality

hash-set! and hash-ref compare keys with equal?, so strings and lists work as keys. Guile also has hashq- procedures, which compare with eq?, and hashv- procedures, which compare with eqv?. A table must always be used with the same family of procedures.

equality.scm
(define (make-key)
  (string-append "ke" "y"))

(define by-equal (make-hash-table))
(define by-identity (make-hash-table))

(hash-set! by-equal (make-key) 'found)
(hashq-set! by-identity (make-key) 'found)

(write (hash-ref by-equal (make-key)))
(newline)
(write (hashq-ref by-identity (make-key)))
(newline)

(define codes (make-hash-table))

(hashq-set! codes 'red 1)
(hashq-set! codes 'green 2)
(write (hashq-ref codes (string->symbol "green")))
(newline)

(define squares (make-hash-table))

(hashv-set! squares 12 144)
(hashv-set! squares 2.5 6.25)
(write (list (hashv-ref squares (* 3 4)) (hashv-ref squares (/ 5.0 2))))
(newline)

make-key builds a new string on each call. The equal? table finds the entry because the strings have the same characters; the eq? table does not, because the lookup key is a different object. For symbols, hashq- is the right choice, since equal symbols are the same object, as the symbols article explains. The hashv- procedures compare numbers by value and exactness: the computed 12 and 2.5 find their entries.

$ guile equality.scm
found
#f
2
(144 6.25)

Counting words

Counting how often each item occurs is a classic use of a hash table. The program counts the words of a short text and then prints the counts in the order in which the words first appear.

words.scm
(define text
  "the cat saw the dog and the dog saw the bird and the cat ran")

(define (count-words words)
  (let ((counts (make-hash-table)))
    (for-each (lambda (word)
                (hash-set! counts word (+ 1 (hash-ref counts word 0))))
              words)
    counts))

(define words (string-split text #\space))
(define counts (count-words words))

(write (hash-count (const #t) counts))
(newline)

(define (unique items)
  (let ((seen (make-hash-table)))
    (filter (lambda (item)
              (if (hash-ref seen item)
                  #f
                  (begin
                    (hash-set! seen item #t)
                    #t)))
            items)))

(for-each (lambda (word)
            (display word)
            (display " ")
            (display (hash-ref counts word))
            (newline))
          (unique words))

(write (hash-fold (lambda (word n best)
                    (if (> n (cdr best)) (cons word n) best))
                  (cons "" 0)
                  counts))
(newline)

count-words increments the count of each word, with 0 as the default for a new word. The text has seven different words. unique uses a second table to remember the words it has already seen and keeps only the first occurrence of each, which fixes the order of the report. The final hash-fold keeps the pair of the most frequent word and its count.

$ guile words.scm
7
the 5
cat 2
saw 2
dog 2
and 2
bird 1
ran 1
("the" . 5)

SRFI 69

SRFI 69 defines a hash table interface that is available in several Scheme implementations. Guile provides it in the (srfi srfi-69) module, which loads without warnings. Its procedures are named hash-table- followed by the operation.

srfi69.scm
(use-modules (srfi srfi-69))

(define scores (make-hash-table))

(hash-table-set! scores "anna" 82)
(hash-table-set! scores "boris" 67)

(write (hash-table-ref/default scores "anna" 0))
(newline)
(write (hash-table-ref/default scores "cyril" 0))
(newline)
(write (hash-table-ref scores "cyril" (lambda () 'no-score)))
(newline)

(hash-table-update!/default scores "boris" (lambda (s) (+ s 10)) 0)
(hash-table-update!/default scores "cyril" (lambda (s) (+ s 10)) 0)

(write (list (hash-table-ref/default scores "boris" 0)
             (hash-table-ref/default scores "cyril" 0)))
(newline)
(write (list (hash-table-size scores)
             (hash-table-exists? scores "anna")
             (hash-table-exists? scores "dana")))
(newline)
(hash-table-delete! scores "anna")
(write (hash-table-keys scores))
(newline)
(write (hash-table-values scores))
(newline)

hash-table-ref/default returns a default for a missing key, and hash-table-ref calls a procedure instead, here one that returns a symbol. hash-table-update!/default applies a procedure to the current value, starting from the default when the key is new, so it replaces the read-and-set pattern of the word counter. hash-table-size returns the number of entries, hash-table-exists? tests a key, and hash-table-keys and hash-table-values return lists.

$ guile srfi69.scm
82
0
no-score
(77 10)
(3 #t #f)
("boris" "cyril")
(77 10)

Case-insensitive keys

SRFI 69's make-hash-table accepts an equality predicate and a matching hash function. Two keys that are equal under the predicate must have the same hash, so a case-insensitive table pairs string-ci=? with string-ci-hash.

caseless.scm
(use-modules (srfi srfi-69))

(define users (make-hash-table string-ci=? string-ci-hash))

(hash-table-set! users "Admin" 'all)
(hash-table-set! users "guest" 'read)

(write (hash-table-ref/default users "ADMIN" 'none))
(newline)
(write (hash-table-ref/default users "Guest" 'none))
(newline)

(hash-table-set! users "GUEST" 'read-write)
(write (hash-table-size users))
(newline)
(write (hash-table-ref/default users "guest" 'none))
(newline)

(define (count-caseless words)
  (let ((counts (make-hash-table string-ci=? string-ci-hash)))
    (for-each (lambda (w)
                (hash-table-update!/default counts w (lambda (n) (+ n 1)) 0))
              words)
    counts))

(define counts (count-caseless (list "Go" "go" "GO" "stop" "Stop" "wait")))
(write (map (lambda (w) (hash-table-ref/default counts w 0))
            (list "go" "stop" "wait")))
(newline)

The keys "Admin" and "ADMIN" are the same in this table. Setting "GUEST" replaces the value of "guest" instead of adding a third entry, so the size stays at two. count-caseless counts the words without regard to case: "Go", "go", and "GO" are three occurrences of one word.

$ guile caseless.scm
all
read
2
read-write
(3 2 1)

Converting to and from association lists

alist->hash-table builds a table from an association list and hash-table->alist goes the other way. SRFI 69 also has its own iteration procedures, hash-table-walk and hash-table-fold.

converting.scm
(use-modules (srfi srfi-69))

(define prices
  (alist->hash-table
   (list (cons 'bread 1.2) (cons 'milk 0.9) (cons 'cheese 4.5))))

(write (hash-table-ref/default prices 'milk 0))
(newline)

(hash-table-walk prices
                 (lambda (item price)
                   (hash-table-set! prices item (* price 1.1))))

(write (hash-table-ref/default prices 'cheese 0))
(newline)

(define (total-cost order)
  (hash-table-fold order
                   (lambda (item amount sum)
                     (+ sum (* amount (hash-table-ref/default prices item 0))))
                   0))

(define order (alist->hash-table (list (cons 'bread 2) (cons 'cheese 1))))

(write (total-cost order))
(newline)
(write (hash-table->alist order))
(newline)

The price list starts as an association list. hash-table-walk raises every price by ten percent. It only replaces the values of existing keys; adding or removing keys during a walk should be avoided. total-cost folds over an order, a table of items and amounts, and multiplies each amount by the price of the item. Note that the arguments of hash-table-fold come in a different order than those of Guile's hash-fold: the table is first.

$ guile converting.scm
0.9
4.95
7.59
((cheese . 1) (bread . 2))

Grouping

A hash table whose values are lists groups items by a key computed from each item. The procedure that computes the key decides how the items are grouped.

grouping.scm
(use-modules (srfi srfi-69))

(define cities
  (list "Prague" "Brno" "Bratislava" "Budapest" "Pecs" "Kosice" "Plzen"))

(define (group-by key items)
  (let ((groups (make-hash-table)))
    (for-each (lambda (item)
                (hash-table-update!/default groups
                                            (key item)
                                            (lambda (group) (cons item group))
                                            '()))
              (reverse items))
    groups))

(define (first-letter s) (string-ref s 0))

(define by-letter (group-by first-letter cities))

(for-each (lambda (letter)
            (display letter)
            (display ": ")
            (write (hash-table-ref/default by-letter letter '()))
            (newline))
          (list #\B #\P #\K #\Z))

(define by-length (group-by string-length cities))
(write (hash-table-ref/default by-length 4 '()))
(newline)

group-by conses each item onto the list stored under its key. It goes through the items in reverse, so the groups keep the original order. Grouping the cities by their first letter gives three groups, and a letter without cities returns the empty default. Grouping by string-length collects the cities with four-letter names.

$ guile grouping.scm
B: ("Brno" "Bratislava" "Budapest")
P: ("Prague" "Pecs" "Plzen")
K: ("Kosice")
Z: ()
("Brno" "Pecs")

Source

Hash Tables — GNU Guile Reference Manual

SRFI-69 — GNU Guile Reference Manual

In this article we have created hash tables, added, updated, and removed entries, iterated over them, used handles to tell missing keys from false values, chosen between equal?, eq?, and eqv? keys, counted words, used the SRFI 69 interface with case-insensitive keys, converted between tables and association lists, and grouped items. The association lists article covers the list-based alternative, and the closures article stores computed results for memoization.

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.