Created
September 20, 2018 04:37
-
-
Save viebel/26a5a21b38ba2d2f3011be7b3cfdc95c to your computer and use it in GitHub Desktop.
a memoized version of a function (even if it is not referentially transparent)
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 transparent [arg] | |
[(type arg) (meta arg) (when (seq? arg) (seq arg)) arg]) | |
(defn memoize-tr | |
"Returns a memoized version of a function (even if it is not referentially | |
transparent). 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." | |
{:added "1.0" | |
:static true} | |
[f] | |
(let [mem (atom {})] | |
(fn [& args] | |
(let [ref-transparent-args (map transparent args)] | |
(if-let [e (find @mem ref-transparent-args)] | |
(val e) | |
(let [ret (apply f args)] | |
(swap! mem assoc ref-transparent-args ret) | |
ret)))))) | |
(def mem-conj (memoize conj)) | |
(println (= (mem-conj [1 2] 3) (conj [1 2] 3))) | |
;; true | |
(println (= (mem-conj '(1 2) 3) (conj '(1 2) 3))) | |
(def mem-tr-conj (memoize-tr conj)) | |
(println (= (mem-tr-conj [1 2] 3) (conj [1 2] 3))) | |
(println (= (mem-tr-conj '(1 2) 3) (conj '(1 2) 3))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment