concurrencyclojurefunctional-programmingagentparallel-assignment

How to create multiple agents in parallel (for? or map?) with name and values in CLOJURE?


I'm trying to make a bunch of agents. Individually, one can do:

(def myAgent (agent 3))

But if I want to make a lot of agents, how can I assign both names and values to the agent in an anonymous function? I have this:

(def agents (vec (map agent (range 0 50)) ))

Which makes 50 agents, but none of them have a value. When I try an anonymous function:

(def agents (vec (map (fn [x] (def x (agent 3)) (range 0 50)) ))

It doesn't work. Any help would be greatly appreciated.


Solution

  • creates a map containing 3 agents whose names are the map keys 0, 1, 2 and the map values are the agents with initial value :initial-value

    user=> (zipmap (range 3) (repeatedly  #(agent :initial-value)))
    {0 #object[clojure.lang.Agent 0x31edaa7d {:status :ready, :val :initial-value}], 
     1 #object[clojure.lang.Agent 0x26adfd2d {:status :ready, :val :initial-value}], 
     2 #object[clojure.lang.Agent 0x3336e6b6 {:status :ready, :val :initial-value}]}