Skip to content

Instantly share code, notes, and snippets.

@pmj
Created October 30, 2010 16:44
Show Gist options
  • Save pmj/655493 to your computer and use it in GitHub Desktop.
Save pmj/655493 to your computer and use it in GitHub Desktop.
memoization with invalidation in clojure
(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