尽管可以使用memo-clear!强制刷新,但我们出于效率考虑而进行缓存,因此提供一个方便的手动设置缓存值的方法将很好。这是一种实现方式
(defn memo-miss!
"Reaches into a core.memo-populated function and sets the cached value
for a given seq of function args."
[f args result]
(when-let [cache (cache-id f)]
(swap! cache clojure.core.cache/miss args (delay result))))
(testing "that setting cache values works as expected"
(is (memo-clear! id))
(is (memo-miss! id [29] :x))
(is (= :x (id 29)))
(is (= 42 (id 42))))
遵循现有代码风格,可以写成如下
(defn memo-miss!
"Reaches into a core.memo-populated function and sets the cached value
for a given seq of function args."
[f args result]
(when-let [cache (cache-id f)]
(swap! cache
(constantly (clojure.core.cache/miss @cache args (delay result))))))
我不明白为什么swap!... constantly经常被首选,或者它与reset!有何不同,但我也不是维护者的数十年的经验!