Maps in Lisp

Create a dictionary:

(let ((m (make-hash-table :test 'equal)))
  ;; set key/value pairs
  (setf (gethash "k1" m) 7)
  (setf (gethash "k2" m) 13)

  ;; print the map
  (format t "map: ~a~%" m)
  
  ;; get a value for a key
  (let ((v1 (gethash "k1" m)))
    (format t "v1: ~a~%" v1))

  ;; if a key doesn’t exist, the zero value (nil) is returned
  (let ((v3 (gethash "k3" m)))
    (format t "v3: ~a~%" v3))

  ;; get the number of key/value pairs
  (format t "len: ~a~%" (hash-table-count m))

  ;; delete a key/value pair
  (remhash "k2" m)
  (format t "map: ~a~%" m)

  ;; clear all key/value pairs
  (clrhash m)
  (format t "map: ~a~%" m)

  ;; check if the key exists
  (multiple-value-bind (value exists-p) (gethash "k2" m)
    (format t "prs: ~a~%" exists-p))

  ;; declare and initialize a map in the same line
  (let ((n (list (cons "foo" 1) (cons "bar" 2))))
    (format t "map: ~a~%" n)
    
    ;; comparing two maps (checking if they are equal)
    (let ((n2 (list (cons "foo" 1) (cons "bar" 2))))
      (when (equal n n2)
        (format t "n == n2~%")))))
  • To create an empty map (dictionary), use make-hash-table with appropriate parameters.
  • Set key/value pairs using setf and gethash.
  • Print the map using format.
  • Retrieve a value using gethash.
  • If a key does not exist, nil is returned.
  • Get the number of key/value pairs using hash-table-count.
  • Delete key/value pairs using remhash.
  • Clear all key/value pairs using clrhash.
  • Check if a key exists by using multiple-value-bind with gethash.
  • Initialize and declare a map in the same line using list and cons.
  • Compare two maps (dictionaries) for equality using equal.