-
-
Save cemerick/48f2974657cdda5f560d to your computer and use it in GitHub Desktop.
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- 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