clrhash
clrhash Function
Syntax:
clrhash hash-table → hash-table
Arguments and Values:
hash-table—a hash table.
Description:
Removes all entries from hash-table, and then returns that empty hash table.
Examples:
(setq table (make-hash-table)) → #<HASH-TABLE EQL 0/120 32004073>
(dotimes (i 100) (setf (gethash i table) (format nil "~R" i))) → NIL
(hash-table-count table) → 100
(gethash 57 table) → "fifty-seven", *true*
(clrhash table) → #<HASH-TABLE EQL 0/120 32004073>
(hash-table-count table) → 0
(gethash 57 table) → NIL, *false*
Side Effects:
The hash-table is modified.
Expanded Reference: clrhash
Basic Usage
clrhash removes all entries from a hash table and returns the now-empty hash table.
(let ((ht (make-hash-table)))
(setf (gethash 'a ht) 1)
(setf (gethash 'b ht) 2)
(hash-table-count ht))
=> 2
(let ((ht (make-hash-table)))
(setf (gethash 'a ht) 1)
(setf (gethash 'b ht) 2)
(clrhash ht)
(hash-table-count ht))
=> 0
Returns the Same Hash Table
clrhash returns the hash table itself, allowing chained operations.
(let ((ht (make-hash-table)))
(setf (gethash 'x ht) 99)
(eq ht (clrhash ht)))
=> T
All Entries Become Inaccessible
(let ((ht (make-hash-table)))
(setf (gethash 'key ht) "value")
(clrhash ht)
(gethash 'key ht))
=> NIL
=> NIL
Resetting a Cache
A practical pattern: clearing a hash table used as a cache to free memory or reset state.
(let ((cache (make-hash-table :test #'equal)))
;; Fill cache
(dotimes (i 100) (setf (gethash i cache) (* i i)))
(format t "Entries before clear: ~D~%" (hash-table-count cache))
(clrhash cache)
(format t "Entries after clear: ~D~%" (hash-table-count cache))
;; Table is ready for reuse
(setf (gethash 0 cache) "fresh")
(gethash 0 cache))
.. Entries before clear: 100
.. Entries after clear: 0
..
=> "fresh"
=> T