Reputation: 79
I'm a beginner with Clojure, and I've read about its concurrency systems like atoms, refs, and agents. What I can't seem to find documentation for is whether you can wrap a data structure in different systems for use in different functions.
Let's say I will represent data like this:
{ :id {:counter 0 :text: ""}, :id2 {:counter 0 :text: ""} }
I wanted to use an atom for updating the counter of individual nested maps, so I defined an atom like this:
(def myAtom (atom {}))
But I guess it would be more convenient to use an agent for just appending new map structures to the wrapping map. Does it then make sense to wrap my atom in an agent like below?
(def myAgent (agent myAtom))
Or does it make more sense to first define a map and wrap it separately in an atom and an agent?
(def myMap {})
(def myAtom (atom myMap))
(def myAgent (agent myMap))
Or is it better to use two separate data structures for these operations and then merge the data later?
Upvotes: 1
Views: 66
Reputation: 29958
Here is how you should do it
(def data (atom {:id {:counter 0 :text ""}, :id2 {:counter 0 :text ""}}))
(println @data)
(swap! data update-in [:id :counter] inc)
(println @data)
(swap! data update-in [:id2 :counter] inc)
(println @data)
with result:
{:id {:counter 0, :text }, :id2 {:counter 0, :text }}
{:id {:counter 1, :text }, :id2 {:counter 0, :text }}
{:id {:counter 1, :text }, :id2 {:counter 1, :text }}
Upvotes: 1