Lisp - Updating Values from a Hash Table



In LISP, we've Hash Table as a fundamental data structure to store key-value pairs. In this chapter, we'll be checking how to add and update values from a hashtable with examples.

Creating and adding values to hash table for numbers/symbols

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

Updating value from the hashtable

We can update an element to a hashtable using setf in conjuction with gethash function as shown below:

(setf (gethash '001 my-hash-table) 10)
  • 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. If key is already present, then associated value is updated.

Example - Adding and Updating Numbers of 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)
; update 001 entry
(setf (gethash '001 my-hash-table) 100)
; 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
100

In case of String, we should use equal function other than default function eql

Example - Adding and Updating Strings of 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))
; Update "apple" entry
(setf (gethash "apple" my-hash-table) 100)
(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
100
Advertisements