更新Clojure原子属性

pdo*_*926 2 clojure

将一个新值合并到一个驻留在原子中的地图中的矢量的惯用方法是什么?

我能够得到的最接近的是:

(def blog (atom {:posts []}))

(swap! 
    blog 
    (fn [current] 
        {:posts (conj (:posts current) {:title "War of Worlds"})}))
Run Code Online (Sandbox Code Playgroud)

结果如下:

{:posts [:title "War of Worlds"]}
Run Code Online (Sandbox Code Playgroud)

使用lambda感觉不必要地冗长.

Ale*_*ler 7

我会做:

(swap! blog update-in [:posts] conj {:title "War of the Worlds"})
Run Code Online (Sandbox Code Playgroud)

互换!和update-in遵循"更新模型"形式,它们可以像这样有利地链接在一起.这是一种非常常见的模式,特别是对于有状态容器和嵌套映射更新.

"更新模型"意味着表单的功能:(defn u [context f & args])调用为(apply f context args).