Skip to content

Instantly share code, notes, and snippets.

@michaeljforster-zz
Last active December 14, 2015 03:19
Show Gist options
  • Select an option

  • Save michaeljforster-zz/5019941 to your computer and use it in GitHub Desktop.

Select an option

Save michaeljforster-zz/5019941 to your computer and use it in GitHub Desktop.
(defmacro defenum (name (&rest keys))
"Define a function named %NAME, that takes an argument KEY and returns
an associated value from KEYS. If KEYS are scalar values, the associated
values are zero-based indices."
(let ((function-name (intern (format nil "%~:@(~A~)" name))))
(flet ((ensure-alist (list)
(let ((i -1))
(mapcar #'(lambda (x)
(destructuring-bind (key &optional (value (incf i)))
(alexandria:ensure-list x)
(cons key value)))
list))))
(alexandria:with-unique-names (hash-table)
`(let ((,hash-table (alexandria:alist-hash-table (ensure-alist ,keys))))
(defun ,function-name (key)
(gethash key ,hash-table))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment