Skip to content

Instantly share code, notes, and snippets.

@cemerick
Created March 10, 2010 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cemerick/327842 to your computer and use it in GitHub Desktop.
Save cemerick/327842 to your computer and use it in GitHub Desktop.
(defn- stateful-memoize
[f #^java.util.Map map]
(fn [& args]
(if-let [e (find map args)]
(val e)
(let [ret (apply f args)]
(.put map args ret)
ret))))
(defn weak-memoize
"Same as memoize, but uses a WeakHashMap for storing argument keys and result values.
**Be aware of what this entails for persistence of values: lose your keys, and
the associated value may get recalculated**"
[f]
(stateful-memoize f (java.util.WeakHashMap.)))
(defn lru-map
[max-size]
(proxy [java.util.LinkedHashMap] []
(removeEldestEntry [entry]
(> (.size #^java.util.Map this) max-size))))
(defn lru-memoize
"Same as memoize, but uses a LinkedHashMap-based LRU cache to ensure that a maximum of
max-size entries are held at any time."
[f max-size]
(stateful-memoize f (lru-map max-size)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment