虽然可以使用 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! 有何不同,但我也没有维护者的几十年经验!