交换原子作为使用函数的最后一个参数

时间:2016-01-05 17:02:28

标签: clojure atomic swap

我有以下功能:

(defn add-recommendations-to-cache [{:keys [trackingId rec-service recs]} cache]
  (assoc-in cache [trackingId rec-service] recs))

我将原子定义为:

(def cache (atom {}))

如果我可以改变传递给函数的参数的顺序,我会使用:

(swap! cache add-recommendations-to-cache msg)

由于我不能,我如何swap使用原子,函数和包含第一个参数所需内容的消息?我尝试了几种可能的组合(见下文),但似乎都没有。

我试过了:

(swap! cache add-recommendations-to-cache msg cache)

(swap! cache (add-recommendations-to-cache msg))

和其他几个没用。

1 个答案:

答案 0 :(得分:7)

您可以传递自己的函数,按照您想要的顺序应用参数:

(swap! cache 
       (fn [current msg] (add-recommendations-to-cache msg current))
       msg)

(swap! cache #(add-recommendations-to-cache %2 %1) msg)

或关闭msg

(swap! cache #(add-recommendataions-to-cache msg %))