Node:Hash Table Examples, Next:Hash Table Reference, Up:Hash Tables
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)) (hashq-create-handle! h 'foo "bar") => (foo . "bar") (hashq-create-handle! h 'braz "zonk") => (braz . "zonk") (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
Better is to use the procedure
hashq-get-handle, which makes a
distinction between the two cases. Just like
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