Lisp - Searching a Hash Table



In LISP, Hashtable is a very efficient data structure to store and search elements due to hash table implementation. In this chapter, we'll explore the search capability of a HashTable in LISP. LiSP provides gethash function to retrieve a value associated with a key in a hashtable.

Syntax - gethash function

gethash key hash-table [default]
  • gethash− a primary function to search a value for a given key. Returns the value associated with the key or default if key is not found.

  • key− the key to be searched.

  • hash-table− hash table to be searched.

  • default− an optional value, returned if key is not present in the hashtable. By default, nil is returned.

Example - Searching in Hashtable of Numbers

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) 
(setf (gethash '003 my-hash-table) 30) 


(defvar value (gethash '001 my-hash-table))
(if value
   (format t "001 found, with value: ~a~%" value)
   (format t "001 not found.~%"))

(defvar value1 (gethash '004 my-hash-table))
(if value1
   (format t "004 found, with value: ~a~%" value1)
   (format t "004 not found.~%"))

Output

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

001 found, with value: 10
004 not found.

Example - Searching in Hashtable of Strings

To create string based keys in a hashtable in LISP, we need to pass the test function to make-hash-table as equals to compare strings in stead of default eql.

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) 
(setf (gethash "orange" my-hash-table) 30) 


(defvar value (gethash "apple" my-hash-table))
(if value
   (format t "apple found, with value: ~a~%" value)
   (format t "apple not found.~%"))

(defvar value1 (gethash '004 my-hash-table))
(if value1
   (format t "mango found, with value: ~a~%" value1)
   (format t "mango not found.~%"))

Output

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

apple found, with value: 10
mango not found.
Advertisements