Lisp - Removing Values from a Hash Table
Hash Table is a data structure to store key-value pairs. In this chapter, we'll be checking how to remove values from a hashtable with examples.
Creating and adding values to hash table for numbers
We can create a hashtable for symbols and numbers with default equality function: eql.
(defvar my-hash-table (make-hash-table)) (setf (gethash '001 my-hash-table) 10)
make-hash-table− make-hash-table without any arguments creates a new hash table my-hash-table.
gethash− retrieves the value associated with key 001 in my-hash-table. If key is not present in table, then nil is returned.
setf− sets the value 10 associated with key 001
Removing value from the hashtable
We can remove value from a hashtable using remhash function.
(remhash '001 my-hash-table)
remhash− remhash the value associated with key 001 in my-hash-table. If key is not present in table, then nil is returned.
Example - Adding and Removing Numbers from Hashtable
main.lisp
; create a hashtable (defvar my-hash-table (make-hash-table)) ; add key-value pairs to hash table (setf (gethash '001 my-hash-table) 10) (setf (gethash '002 my-hash-table) 20) ; print the value for 001 from hashtable (write (gethash '001 my-hash-table)) ; terminate printing (terpri) ; remove 001 entry (remhash '001 my-hash-table) ; print the value for 001 from hashtable (write (gethash '001 my-hash-table))
Output
When you execute the code, it returns the following result −
10 NIL
In case of String, we should use equal function other than default function eql
Example - Adding and Removing Strings from Hashtable
main.lisp
; create a hashtable (defvar my-hash-table (make-hash-table :test #'equal)) ; add key-value pairs to hash table (setf (gethash "apple" my-hash-table) 10) (setf (gethash "banana" my-hash-table) 20) ; print the value for "apple" from hashtable (write (gethash "apple" my-hash-table)) ; remove "apple" entry (remhash "apple" my-hash-table) (terpri) ; print the value for "apple" from hashtable (write (gethash "apple" my-hash-table))
Output
When you execute the code, it returns the following result −
10 NIL