Email: lhao@cs.uml.edu

Last Update: July 02, 2003
 

LISP Source Code Depot

Home

Artificial Intelligence
LISP

Hash Table

Contents

 

Prints All Entries in a Hash Table (back)

The function print-hash can print out all entries of a hash table. Especially, if a hash table is nested (i.e., some of entries are hash tables), this function could output the entries with indentation for readability.

(defun print-hash (hash &optional (indent 0))
  (maphash #'(lambda (key value)
	       (do ((i 0 (+ i 1)))
		   ((>= i indent))
		 (format t " "))
	       (format t "~A = ~A~%" key value)
	       (when (hash-table-p value)
		 (print-hash value (+ 2 indent))))
	   hash))

Example: We create three hash tables ht1, ht2 and ht. The ht1 has two pairs (1, Jan) and (2, Feb) and the ht2 has one pair (color, red). The ht contains two pairs (key-1, ht1) and (key-2, ht2). The outcome of print-hash function is shown as follows:

>(print-hash ht)
key-1 = #<EQL hash-table with 2 entries>
  1 = JAN
  2 = FEB
key-2 = #<EQL hash-table with 1 entry>
  COLOR = RED

 

Query a Hash Table and Returns a List of Keys that Satisfy Specific Predicates (back)

The function query-hash takes two arguments. The first argument is a function that takes a key and a value as arguments and returns T or NIL. The second argument is a hash table. The query-hash function will traverse and apply the provided function onto every (key, value) pair in the hash table. If the provided function returns T for a given (key, value) pair, this key will be appended into the resulting list.

(defun query-hash (function hash)
  (let ((found-list ()))
    (maphash #'(lambda (key value)
                 (when (funcall function key value)
                   (setf found-list (append found-list (list key)))))
             hash)
    found-list))
Example: We have a hash table called age that contains the U.S. age distribution in percent in 1990 and 2000 as follows. Here, the keys are age ranges, and the values are a two-element list whose first element is the distribution in percent in 1990 and the second element is in 2000.
0-4 = (7.4 6.8)
5-14 = (14.2 14.6)
15-24 = (14.8 13.9)
25-34 = (17.4 14.2)
35-44 = (15.1 16.0)
45-54 = (10.1 13.4)
55-64 = (8.5 8.6)
65-74 = (7.3 6.5)
75-84 = (4.0 4.4)
85+ = (1.2 1.5)

Now, we wonder the age ranges in 2000 whose distributions in percent are greater than 10%. We can use query-hash function as follows:

>(query-hash #'(lambda (key value)
                 (if (> (car (last value)) 10) T nil)) age)
(25-34 35-44 45-54 5-14 15-24)

 

 

© 2003. All rights reserved.