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.

5
  • "makes 50 agents, but none of them have a value" - everything in clojure has a value Commented Oct 9, 2015 at 6: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? Commented Oct 9, 2015 at 6:08
  • @ProgrammingEqualsSuperpower you must supply initial value when creating agent. you cannot create agent just by doing (agent) Commented Oct 9, 2015 at 6: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. Commented Oct 9, 2015 at 6: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. Commented Oct 9, 2015 at 15:55

1 Answer 1

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}]} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.