Skip to content

Instantly share code, notes, and snippets.

@viebel
Created September 20, 2018 04:37
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 viebel/26a5a21b38ba2d2f3011be7b3cfdc95c to your computer and use it in GitHub Desktop.
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)
(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