Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a memoized version of a function (even if it is not referentially transparent)
(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
You can’t perform that action at this time.