cold
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?
Marked As Solved
idi527
![]()
&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)
true
iex(3)> is_map(agent)
false
iex(4)> bucket = Agent.get(agent, fn bucket -> bucket end)
%{}
iex(5)> is_map(bucket)
true
iex(7)> Agent.update(agent, fn bucket -> Map.put(bucket, :milk, 3) end)
:ok
iex(8)> Agent.get(agent, fn bucket -> bucket end)
%{milk: 3}
iex(9)> Agent.get(agent, fn bucket -> Map.get(bucket, :milk) end)
3
iex(10)> Agent.get(agent, &Map.get(&1, :milk))
3
iex(11)> Agent.get(agent, & &1)
%{milk: 3}
Also Liked
cold
Now I understand, thanks!
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









