Lisp - Adding Values to a Hash Table



Hash Table in LISP is a fundamental data structure to store key-value pairs. In this chapter, we'll be adding values to a hashtable with examples.

Create a 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))

Adding element to the hashtable

We can add 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

Retrieving value from the hashtable

We can retrieve value from a hashtable using gethash function.

(gethash '001 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.

Example - Adding and Retrieving 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)
; print the value for 002 from hashtable
(write (gethash '002 my-hash-table))  

Output

When you execute the code, it returns the following result −

10
20

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

Example - Adding and Retrieving 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))
; terminate printing 
(terpri)
; print the value for "banana" from hashtable
(write (gethash "banana" my-hash-table))  

Output

When you execute the code, it returns the following result −

10
20
Advertisements