0

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.

ProGrammar
  • 298
  • 4
  • 17
  • "makes 50 agents, but none of them have a value" - everything in clojure has a value – noisesmith Oct 09 '15 at 06:06
  • Ok, well, i'm very amateur with clojure, but wracking my brain trying to figure this out, and it is not anywhere online, at least that I can find. Isn't that what this place is for? Why down-vote and not help? – ProGrammar Oct 09 '15 at 06:08
  • @ProgrammingEqualsSuperpower you must supply initial value when creating agent. you cannot create agent just by doing (agent) – mavbozo Oct 09 '15 at 06:17
  • I don't understand what the accepted answer does that the supposedly not working code here doesn't (other than being a hash map vs. a vector, both are indexed by numeric key, both contain agents, the agents in both cases are initialized to some starting value). I have no idea what the code in your question fails to do that you need. – noisesmith Oct 09 '15 at 06:33
  • So, I wrote it wrong. When I do the above, corrected, (def agents (vec (map (fn [x] (def x (agent 3)) (range 0 50)) )) It gives me a vector of 50 agents containing the value 3, but they're all assigned to x, and not the unique numbers I was tying to have x represent. – ProGrammar Oct 09 '15 at 15:55

1 Answers1

2

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}]}
mavbozo
  • 1,161
  • 8
  • 10