Created
October 30, 2010 16:44
-
-
Save pmj/655493 to your computer and use it in GitHub Desktop.
memoization with invalidation in clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn memoize* | |
"Like clojure.core/memoize, but the returned function's metadata contains an :invalidate function which completely resets the memory in the 0-ary form, or accepts the argument sequence for which to invalidate as its only argument." | |
[f] | |
(let [memo (atom {})] | |
(with-meta | |
(fn memoized [& args] | |
(if-let [e (find @memo args)] | |
(val e) | |
(let [ret (apply f args)] | |
(swap! memo assoc args ret) | |
ret))) | |
{:invalidate | |
(fn memo-invalidate | |
; invalidate all | |
([] | |
(reset! memo {})) | |
([args] | |
(swap! memo dissoc (seq args))))}))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment