Next: , Up: Hash Tables


5.6.12.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>
     
     ;; We can also use a vector of alists.
     (define h (make-vector 7 '()))
     
     h
     =>
     #(() () () () () () ())
     
     ;; 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)
     
     ;; The vector now contains three elements in the alists and the frob
     ;; entry is at index (hashq 'frob).
     h
     =>
     #(() () () () ((frob . #f) (braz . "zonk")) () ((foo . "bar")))
     
     (hashq 'frob)
     =>
     4
     

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

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

There is no procedure for calculating the number of key/value-pairs in a hash table, but hash-fold can be used for doing exactly that.

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