6.6.22.1 Hash Table Examples

For demonstration purposes, this section gives a few usage examples of some hash table procedures, together with some explanation what they do.

First we start by creating a new hash table with 31 slots, and populate it with two key/value pairs.

(define h (make-hash-table 31))

;; This is an opaque object
h
⇒
#<hash-table 0/31>

;; Inserting into a hash table can be done with hashq-set!
(hashq-set! h 'foo "bar")
⇒
"bar"

(hashq-set! h 'braz "zonk")
⇒
"zonk"

;; Or with hash-create-handle!
(hashq-create-handle! h 'frob #f)
⇒
(frob . #f)

You can get the value for a given key with the procedure hashq-ref, but the problem with this procedure is that you cannot reliably determine whether a key does exists in the table. The reason is that the procedure returns #f if the key is not in the table, but it will return the same value if the key is in the table and just happens to have the value #f, as you can see in the following examples.

(hashq-ref h 'foo)
⇒
"bar"

(hashq-ref h 'frob)
⇒
#f

(hashq-ref h 'not-there)
⇒
#f

It is often better is to use the procedure hashq-get-handle, which makes a distinction between the two cases. Just like assq, this procedure returns a key/value-pair on success, and #f if the key is not found.

(hashq-get-handle h 'foo)
⇒
(foo . "bar")

(hashq-get-handle h 'not-there)
⇒
#f

Interesting results can be computed by using hash-fold to work through each element. This example will count the total number of elements:

(hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
⇒
3

The same thing can be done with the procedure hash-count, which can also count the number of elements matching a particular predicate. For example, count the number of elements with string values:

(hash-count (lambda (key value) (string? value)) h)
⇒
2

Counting all the elements is a simple task using const:

(hash-count (const #t) h)
⇒
3