typestar

Hash tables in Lisp

A spice shelf keyed by strings, which needs :test 'equal rather than the default.

;; :TEST 'EQUAL makes string keys work; the default EQL only matches
;; numbers, characters, and identical objects.
(defvar *shelf* (make-hash-table :test 'equal))

(setf (gethash "cumin" *shelf*) 3)
(setf (gethash "saffron" *shelf*) 1)
(setf (gethash "paprika" *shelf*) 2)

;; The third argument to GETHASH is the value to report for a key
;; that is not on the shelf.
(defvar *cumin* (gethash "cumin" *shelf*))
(defvar *cloves* (gethash "cloves" *shelf* 0))

(format t "~a spices, cumin ~a, cloves ~a~%"
        (hash-table-count *shelf*) *cumin* *cloves*)

;; MAPHASH walks every pair, in no order you should count on.
(maphash (lambda (spice jars) (format t "~a x~a~%" spice jars)) *shelf*)

How it works

  1. (make-hash-table :test 'equal) compares string keys by contents; (setf (gethash "cumin" *shelf*) 3) stores a count.
  2. (gethash "cloves" *shelf* 0) supplies a default for a key that is absent.
  3. (hash-table-count *shelf*) reports the size and maphash walks every pair in unspecified order.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
686
Tokens
89
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 1 of 3 in Collections, step 16 of 27 in Language basics.

← Previous Next →