In many real applications (I guess that rules out fibonacci), memoize
will consume a lot of memory and create OutOfMemoryErrors sooner or
later. Often you want to only keep the latest items in the cache and
forget about older ones.

I've seen a variant of memoize that evicts items based on a time-to-
live bound in this group (http://groups.google.com/group/clojure/
browse_thread/thread/402c489f805ade94/ ).

And here's a variant that evicts elements when the size of the cache
exceeds some limit. In that case, the first item that was put in it
will be dissoc'ed. I'm using an array-map to accomplish this:

(defn bounded-memoize
  [f bound]
  (let [mem (atom (array-map))]
    (fn [& args]
      (if-let [e (find @mem args)]
        (val e)
        (let [ret (apply f args)]
          (swap! mem #(let [new-mem (assoc % args ret)]
                        (if (> (count new-mem) bound)
                          (dissoc new-mem (first (first new-mem)))
                          new-mem)))
          ret)))))

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to