Elisp Data Structures: Hash Tables
Table of Contents
Elisp has 2 types of KV collections. Hash table is unordered set of KV pairs with no duplicate keys and constant access time; Association list is ordered set of KV pairs with possibly repeated keys.
1. Creating Hash Table
(make-hash-table :test 'OPTION)
Returns a new hash table. The :test 'OPTION is to specify what test to check key match. OPTION can be one of: 'eql (default), 'eq, 'equal.
Usually, for strings, use 'equal; for symbols and integers, use 'eq; for floating number keys, use 'eql.
2. Useful Operations
2.1. Length
Use hash-table-count function.
(hash-table-count HASH-TABLE)
2.2. Modification
Add entries. Use puthash function.
(puthash KEY VALUE TABLE)
Remove certain entry. Use remhash function
(remhash KEY TABLE)
Remove all entries. Use clrhash function (clear hash).
(clrhash HASH-TABLE)
2.3. Transformation
We use invoke maphash to apply a function to all entries in a hash table. The function must take 2 arguments.
(maphash FUNCTION HASHTABLE)
;; e.g.
(maphash
(lambda (k v)
(princ (format "%s, %s" k v))
(princ "\n"))
HASHTABLE)
2.4. Retrieval
Get single item. Use gethash to get value from hash table or optional default value. gethash can also be used to check key existence.
(gethash KEY TABLE &optional DEFAULT)
Get all keys. Use hash-table-keys to return a list of keys.
(hash-table-keys HASHTABLE)
Get all values. Use hash-table-values to return a list of values.
(hash-table-values HASHTABLE)