What is the value of &1 in this Agent.get call?

Hi, I’m studying agents in elixir reading this page https://elixir-lang.org/getting-started/mix-otp/agent.html.
I don’t completely got how is this line working:

                                       Agent.get(bucket, &Map.get(&1, key))

I understand that to use a named function as a parameter we need to use ‘&’ before the function’s name but what does &1 means in this case? Is it the bucket? I tried to verify it by updating a map to the bucket:

                                     Agent.update(bucket, fn _x -> %{milk: 3} end)

And then I used Map.get like this ~> Map.get(bucket, :milk) , so I got the following error:

" ** (BadMapError) expected a map, got: #PID<0.100.0>
(elixir) lib/map.ex:437: Map.get(#PID<0.100.0>, :milk, nil)"

So I guess that the &1 is not the bucket, so what it is?


&Map.get(&1, key)) gets translated into fn first_arg -> Map.get(first_arg, key) end where first_arg is &1.

So I guess that the &1 is not the bucket, so what it is?

&1 is the state of an agent and in case of your particular agent it is indeed the bucket (as a map). The error is probably due to you using the pid of the agent instead of its state.

iex(1)> {:ok, agent} = Agent.start_link(fn -> _bucket = %{} end)
{:ok, #PID<0.113.0>}
iex(2)> is_pid(agent)
iex(3)> is_map(agent)
iex(4)> bucket = Agent.get(agent, fn bucket -> bucket end)
iex(5)> is_map(bucket)
iex(7)> Agent.update(agent, fn bucket -> Map.put(bucket, :milk, 3) end)
iex(8)> Agent.get(agent, fn bucket -> bucket end)
%{milk: 3}
iex(9)> Agent.get(agent, fn bucket -> Map.get(bucket, :milk) end)
iex(10)> Agent.get(agent, &Map.get(&1, :milk))
iex(11)> Agent.get(agent, & &1)
%{milk: 3}

Now I understand, thanks!

1 Like