On

6 views
Skip to first unread message

samppi

unread,
Oct 4, 2009, 4:41:03 PM10/4/09
to Clojure
I want to do this:

(defn a ...)
(cache a) ; or (cache #'a) or (cache 'a); it doesn't matter to me

...instead of this:

(def a (memoize (fn ...)))

That way, it separates the concern of what a does from the
optimization I'm doing on it. Now, I'm kind of stuck; how should I do
it?

(defn cache
"Replaces the function that the given variable refers to
with a memoizing version of it."
[fn-var]
(??? fn-var (memoize @fn-var)))

talk

unread,
Oct 4, 2009, 4:47:52 PM10/4/09
to Clojure
Oops; I didn't finish this thread's subject title.

Meikel Brandmeyer

unread,
Oct 4, 2009, 5:58:48 PM10/4/09
to clo...@googlegroups.com
Hi,

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

talk

unread,
Oct 4, 2009, 6:50:23 PM10/4/09
to Clojure
What a lifesaver! Thanks a lot!
>  smime.p7s
> 3KViewDownload

John Harrop

unread,
Oct 4, 2009, 9:25:35 PM10/4/09
to clo...@googlegroups.com
Why not use a macro?

(defmacro cache
  "Replaces the function that the given variable refers to
   with a memoizing version of it."
  [fn-var-name]
  `(def ~fn-var-name (memoize ~fn-var-name)))

Chouser

unread,
Oct 5, 2009, 12:03:16 PM10/5/09
to clo...@googlegroups.com
On Sun, Oct 4, 2009 at 4:41 PM, samppi <rbys...@gmail.com> wrote:
>

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

Reply all
Reply to author
Forward
0 new messages