On 30 August 2014 06:26, Colin Fleming <colin.mailingl...@gmail.com> wrote: > > I want to use a map to cache values based on a key. I'm planning to use an > atom for this. My basic operation is "give me the value for this key" - if > the value exists in the map then that value should be returned, otherwise a > new value should be calculated, inserted in the map and then returned. My > plan is to implement something like the following: > > > (defn ensure [cache key] > (if (contains? cache key) > cache > (assoc cache key (calc-value key)))) > > (let [value (get (swap! cache ensure key) key)] > ... do my thing with value ...)
Why not just use memoize? (def calc-value (memoize (fn [key] ...)) If you need more control over the cache, check out core.memoize (which builds on top of core.cache). Ray. -- 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 --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.