Skip to content

Instantly share code, notes, and snippets.

@emdeesee
Last active January 5, 2019 00:15
Show Gist options
  • Save emdeesee/a6d0981fb53a35850d9b08393d4183f2 to your computer and use it in GitHub Desktop.
Save emdeesee/a6d0981fb53a35850d9b08393d4183f2 to your computer and use it in GitHub Desktop.
Functionality like Python's ChainMap in Common Lisp
(defun make-chain-table (&rest tables)
(lambda (key)
(labels ((aux (tables)
(if (null tables)
(values nil nil)
(multiple-value-bind (value found) (gethash key (car tables))
(if found
(values value t)
(aux (cdr tables)))))))
(aux tables))))
@emdeesee
Copy link
Author

emdeesee commented Oct 7, 2018

Usage

cl-user> (defvar *electronics* (make-hash-table :test #'equal))
*ELECTRONICS*
cl-user> (defvar *toys* (make-hash-table :test #'equal))
*TOYS*
cl-user> (defvar *clothes* (make-hash-table :test #'equal))
*CLOTHES*
cl-user> (setf (gethash *toys* "Cheat Commandos: Gunhaver") 24)
24
cl-user> (setf (gethash *toys* "Star Wars Gonk Droid Action Figure") 12)
12
cl-user> (setf (gethash *electronics* "Steam Machine") 8)
128
cl-user> (setf (gethash *electronics* "HP48") 16)
16
cl-user> (setf (gethash *clothes* "Oxford Shirt (Blue)") 12)
12
cl-user> (setf (gethash *clothes* "Loud Socks") 11)
11
cl-user> (defvar *inventory* (make-chain-table *clothes* *electronics* *toys*))
*INVENTORY*
cl-user> (funcall *inventory* "HP48")
16
T
cl-user (funcall *inventory* "Espadrilles")
NIL
NIL
cl-user> _

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment