How to programatically name agents?

Hi I’m an Elixir beginner,

I have been experimenting with agents, basically I was able to create several agents, naming each with unique atoms and changing their internal states. However, now I’m trying to programmatically name the created agents as this would be useful if I were trying to create 1000 agents.
Initially my intention was to use something like Enum.range(1…1000) to creaete 1000 agents and then programatically assign the name of each Agent with the corresponding number so that I can call each Agent by their number: Agent.get(23, fn(x)-> x+1 end), for example to increment agent number 23.
I realised that Elixir doesn’t allow agents to be named by number!

Can someone please tell me how can I do the above? or if there is an easier way to programatically name 1000 agents and retrieve them? I don’t mind if this was doable by using atoms or even pids as well.

Thanks a lot in advance

You could use a Registry and give explicit names to your agents.

Something like this will create you 1000 Agents, giving them an unique name.

Registry.start_link(keys: :unique, name: MyAgents)
|> i -> Agent.start_link(fn -> 0 end, name: {:via, Registry, {MyAgents, i}}) end)

As explained in the documentation, you ca use the name to interact with them:

Agent.get({:via, Registry, {MyAgents, 1}}, & &1)
Agent.update({:via, Registry, {MyAgents, 1}}, & &1 + 1)
Agent.get({:via, Registry, {MyAgents, 1}}, & &1)

If you want a more in-depth explanation, I found this post to be quite good.


huge thanks. That is what I wanted :slight_smile: