Using Clojure's core.cache

Nov 12, 2014   #clojure  #cache 

core.cache is a great Clojure library for caching arbitrary values in your application. Unfortunately, its examples have a minor dissent that can make it hard for a first time user to interact with it.

The usage examples tell you to do this:

(def C (cache/fifo-cache-factory {:a 1, :b 2})) (if (cache/has? C :c) (cache/hit C :c) (cache/miss C :c 42)) ; => {:a 1, :b 2, :c 42}

The naive first time user (that I was) could now assume that there’s some magic going on behind the doors which does some state manipulation and another call to (cache/has? C :c) should return true. But as you guessed it: No magic to see here.

The point is, that cache/miss and cache/hit return a new cache instance with the new value associated. You’ll have to do the state manipulation yourself (e.g. by using an atom):

(def C (atom (cache/fifo-cache-factory {:a 1, :b 2}))) (if (cache/has? @C :c) (swap! C #(cache/hit % :c)) (swap! C #(cache/miss % :c 42))) ; => {:a 1, :b 2, :c 42} (cache/has? @C :c) ; => true