Exadra37

Exadra37

Agent.get_and_update/2 docs example doesn't return what I expect

After some months out of Elixir I am trying to refresh my knowledge on it, therefore I am going through the Elixir for Programmers 2 from @pragdave, because I have done the first edition and it was the one that made made my brain click in the functional programming paradigm.

So I am now at the Agent lesson and he shows the same example we can see in the docs:

iex(12)> Agent.get_and_update(counter, fn state -> {state, state + 1} end)
2
iex(13)> Agent.get(counter, fn state -> state end)                        
3

So, from the function name I would expect to have back the new state, but instead I got back the old state. I know I can control that from the anonymous function I pass, but my question is why the example in the docs is done this way and not this way:

Agent.get_and_update(counter, fn state -> state = state + 1; {state, state} end)    
4
iex(15)> Agent.get_and_update(counter, fn state -> state = state + 1; {state, state} end)
5
iex(16)> Agent.get_and_update(counter, fn state -> state = state + 1; {state, state} end)

I am not seeing immediately how useful it can be to update a state in the Agent and get back the old state, instead of the new state, but for sure it will exist some use cases for it.

Wouldn’t be better to have the official docs showing an example that returns the updated state?

Most Liked

l00ker

l00ker

I think what may not be clear at first is that get_and_update/3 gives you control over what is returned vs what is state. The control over what is returned is what is useful in real world projects.

iex(1)> {:ok, pid} = Agent.start_link(fn -> 42 end)                             
{:ok, #PID<0.113.0>}
iex(2)> Agent.get_and_update(pid, fn state -> {:ok, state + 1} end)             
:ok
iex(3)> Agent.get(pid, fn state -> state end)                                   
43
iex(4)> Agent.get_and_update(pid, fn state -> {"ok", state + 1} end)
"ok"
iex(5)> Agent.get(pid, fn state -> state end)                       
44
iex(6)> Agent.get_and_update(pid, fn state -> {{:ok, state + 1}, state + 1} end)
{:ok, 45}
iex(7)> Agent.get(pid, fn state -> state end)                                   
45

It keeps the state – in this case, only an integer – completely separate from what is returned (think pattern matching). It’s even useful with get/3.

iex(8)> Agent.get(pid, fn state -> {:ok, state} end)
{:ok, 45}
iex(9)> Agent.get(pid, fn state -> state end)       
45
iex(10)> Agent.get(pid, fn state -> %{my_value: state} end)
%{my_value: 45}
kokolegorille

kokolegorille

I guess it would be called update_and_get ?! :slight_smile:

Where Next?

Popular in Questions Top

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement