将新值组合到驻留在映射、原子中的向量中的惯用方法是什么?
我所能达到的最接近结果如下:
(def blog (atom {:posts []}))
(swap!
blog
(fn [current]
{:posts (conj (:posts current) {:title "War of Worlds"})}))
结果是:
{:posts [:title "War of Worlds"]}
使用 lambda 感觉过于冗长。
最佳答案
我会这样做:
(swap! blog update-in [:posts] conj {:title "War of the Worlds"})
两者互换!和 update-in 遵循“更新模型”形式,并且它们可以像这样链接在一起以获利。这是一种非常常见的模式,特别是在有状态容器和嵌套映射更新的情况下。
“更新模型”表示以下形式的函数:(defn u [context f & args])
作为 (apply f context args)
调用。
关于clojure - 更新 Clojure 原子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26520371/