Am 04.10.2009 um 22:47 schrieb talk:
>> (defn cache
>> "Replaces the function that the given variable refers to
>> with a memoizing version of it."
>> [fn-var]
>> (??? fn-var (memoize @fn-var)))
Macros to the rescue:
(defmacro cache
"Replaces the function that the given name refers to
with a memoizing version of it."
([fn-sym] `(cache ~fn-sym ~fn-sym))
([fn-cached fn-uncached]
`(let [var-meta# (meta (var ~fn-uncached))]
(def ~fn-cached (memoize ~fn-uncached))
(reset-meta! (var ~fn-cached) var-meta#)
(var ~fn-cached))))
Sincerely
Meikel
Test function:
(defn foo [i] (println "cache-miss") i)
user=> (foo 5)
cache-miss
5
Utility:
(defn memoize-var [v] (alter-var-root v memoize))
Example usage:
(memoize-var #'foo)
user=> (foo 5)
cache-miss
5
user=> (foo 5)
5
--Chouser