pdoherty926
pdoherty926

Reputation: 10399

Update Clojure atom property

What is the idiomatic way to conj a new value into a vector which resides in a map, in an atom?

The closest I've been able to come is the following:

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

(swap! 
    blog 
    (fn [current] 
        {:posts (conj (:posts current) {:title "War of Worlds"})}))

Which results in:

{:posts [:title "War of Worlds"]}

The use of a lambda feels unnecessarily verbose.

Upvotes: 2

Views: 242

Answers (1)

Alex Miller
Alex Miller

Reputation: 70239

I would do:

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

Both swap! and update-in follow the "update model" form and they can be profitably chained together like this. This is a very common pattern, particularly with a stateful container and nested map update.

"Update model" meaning functions of the form: (defn u [context f & args]) invoked as (apply f context args).

Upvotes: 7

Related Questions