doomemacs/core/autoload/memoize.el

31 lines
1019 B
EmacsLisp

;;; memoize.el
(provide 'doom-lib-memoize)
;;;###autoload
(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.")
;;;###autoload
(defun doom-memoize (name)
"Memoizes an existing function. NAME is a symbol."
(let ((func (symbol-function name)))
(put name 'function-documentation
(concat (documentation func) " (memoized)"))
(fset name
`(lambda (&rest args)
(let ((key (cons ',name args)))
(or (gethash key doom-memoized-table)
(puthash key (apply ',func args)
doom-memoized-table)))))))
;;;###autoload
(defmacro def-memoized! (name arglist &rest body)
"Create a memoize'd function. NAME, ARGLIST, DOCSTRING and BODY
have the same meaning as in `defun'."
(declare (indent defun) (doc-string 3))
`(progn
(defun ,name ,arglist ,@body)
(doom-memoize ',name)))