Last active
June 28, 2017 16:24
-
-
Save rwat/4abcebcb4cfae956f382 to your computer and use it in GitHub Desktop.
generalizes and makes transparent the use of clojure.core.cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns foo | |
(:require [clojure.core.cache :as cache])) | |
(defn cache-interact | |
[the-agent the-function & the-items] | |
"Generalizes the interaction of performing c.c.cache operations by | |
transparently retrieving something from a cache or running the supplied | |
function outside of the agent's thread to generate a value" | |
(let [delay-func (delay (apply the-function the-items)) | |
the-promise (promise) | |
agent-fn (fn [cache- d p & xs] | |
(let [x (first xs)] | |
(if (cache/has? cache- x) | |
(do | |
(deliver p (get cache- x)) | |
(cache/hit cache- x)) | |
(do | |
(deliver p d) | |
(cache/miss cache- x d)))))] | |
(apply send the-agent agent-fn delay-func the-promise the-items) | |
@@the-promise)) | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
(comment | |
(let [c (agent (cache/lirs-cache-factory {} :threshold 100)) | |
f (fn [x] (do (Thread/sleep 1000) {x (identity x)}))] | |
(cache-interact c f :x) | |
(cache-interact c f :y) | |
(cache-interact c f :x)) | |
=> {:x :x} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the inspiration! After thinking about it a bit I wonder what you think of the following version:
It doesn't need the promises and seems more simple.