Created
June 28, 2016 05:08
-
-
Save skrat/d29203738a3e855ff7eab4df7fc9e470 to your computer and use it in GitHub Desktop.
mem.cljs
This file contains hidden or 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-async | |
"Returns a memoized version of a referentially transparent function. The | |
memoized version of the function keeps a cache of the mapping from arguments | |
to results and, when calls with the same arguments are repeated often, has | |
higher performance at the expense of higher memory use. | |
http://stackoverflow.com/questions/24698536/" | |
[f] | |
(let [mem (atom {})] | |
(fn [& args] | |
(go | |
(let [v (get @mem args lookup-sentinel)] | |
(if (identical? v lookup-sentinel) | |
(let [ret (<! (apply f args))] | |
(print "MISS" args (contains? (set (keys @mem)) args)) | |
(swap! mem assoc args ret) | |
ret) | |
(do (print "HIT!") v))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment