I've been reading a bit about the STM, and here's an implementation of a 
FIFO cache for producing a memoized version of a function. Is it correct to 
use the STM in this case, or are there any  drawbacks?
 
(defn bounded-memoize
  "Return a bounded memoized version of fn 'f'
   that caches the last 'k' computed values"
  [f k]
  (let [cache (ref {})
        values (ref clojure.lang.PersistentQueue/EMPTY)]
    (fn [& args]
      (if-let [e (find @cache args)]
        (val e)
        (let [result (apply f args)]
          (dosync
           (alter values conj args)
           (alter cache assoc args result)
           (if (> (count @values) k)
             (let [evict (peek @values)]
               (alter values pop)
               (alter cache dissoc evict))
             )
           result
           ))

        )
      ))
  )


-- 
-- 
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