doomemacs/core/autoload/memoize.el

27 lines
942 B
EmacsLisp
Raw Normal View History

2017-02-13 04:53:55 -05:00
;;; memoize.el
(provide 'doom-lib-memoize)
2017-02-13 04:53:55 -05:00
(defvar doom-memoized-table (make-hash-table :test 'equal :size 10)
"A lookup table containing memoized functions. The keys are argument lists,
and the value is the function's return value.")
2017-02-13 04:53:55 -05:00
(defsubst doom--memoize-wrap (name)
2017-02-13 04:53:55 -05:00
"Return the memoized version of FUNC."
(let ((func (symbol-function name)))
`(lambda (&rest args)
,(documentation name)
(let ((key (cons ',name args)))
(or (gethash key doom-memoized-table)
(puthash key (apply ',func args) doom-memoized-table))))))
2017-02-13 04:53:55 -05:00
(defmacro def-memoized! (name arglist &rest body)
2017-02-13 04:53:55 -05:00
"Create a memoize'd function. NAME, ARGLIST, DOCSTRING and BODY
have the same meaning as in `defun'."
(declare (indent defun) (doc-string 3))
(when (stringp (car body))
(setcar body (concat (car body) " (memoized)")))
2017-02-13 04:53:55 -05:00
`(progn
(defun ,name ,arglist ,@body)
(fset ',name (doom--memoize-wrap ',name))))
2017-02-13 04:53:55 -05:00