2017-02-13 04:53:55 -05:00
|
|
|
;;; memoize.el
|
|
|
|
|
2017-03-01 23:45:39 -05:00
|
|
|
;;;###autoload
|
2017-03-01 23:43:31 -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
|
|
|
|
2017-03-02 00:42:58 -05:00
|
|
|
;;;###autoload
|
|
|
|
(defun doom-memoize (name)
|
|
|
|
"Memoizes an existing function. NAME is a symbol."
|
2017-03-01 23:43:31 -05:00
|
|
|
(let ((func (symbol-function name)))
|
2017-03-02 00:42:58 -05:00
|
|
|
(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)))))))
|
2017-02-13 04:53:55 -05:00
|
|
|
|
2017-03-01 23:45:39 -05:00
|
|
|
;;;###autoload
|
2017-02-23 00:06:12 -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))
|
|
|
|
`(progn
|
|
|
|
(defun ,name ,arglist ,@body)
|
2017-03-02 00:42:58 -05:00
|
|
|
(doom-memoize ',name)))
|
2017-02-13 04:53:55 -05:00
|
|
|
|