brenocastelo

brenocastelo

There's any difference between map.put/3 and the built in Map update %{map | "key" => "value"}?

Hello, guys!

I was doing some exercises from exercism.io and in some moment a needed to update a Map, I did and finished the exercise. After a while, I found the function Enum.frequencies/1 that could have helped me on the exercise. I decided open Elixir source code to see implementation of Enum.frequencies/1 that is this:

  @doc since: "1.10.0"
  @spec frequencies(t) :: map
  def frequencies(enumerable) do
    reduce(enumerable, %{}, fn key, acc ->
      case acc do
        %{^key => value} -> %{acc | key => value + 1}
        %{} -> Map.put(acc, key, 1)
      end
    end)
  end

Then, the question came to me: There’s any difference between map.put/3 and the built in Map update %{map | “key” => “value”}?

I write my version of Enum.frequencies/1 using Enum.reduce/3, and I replaced %{^key => value} -> %{acc | key => value + 1} by %{^x => value} -> Map.put(acc, x, value + 1) and did work.
I would like to know if there is any reason for Elixir source code to use this syntax %{acc | key => value + 1} on Enum.frequencies/1

Most Liked

tovarchristian21

tovarchristian21

Hey, nice to see you are checking source code for solving doubts. Yes there’s a difference, when you update a map using the | operator, that key has to exist already. That is the reason on the case, if the key already exists they just increase the counter by updating the map using the | operator, but if the key is not present yet, the added it using the Map.put/3 function.

eksperimental

eksperimental

This is the equivalent of doing Map.update(acc, key, 1, &(&1 + 1))

derek-zhou

derek-zhou

In erlang, Map#{key => Value} means update or insert, and Map#{key := Value} means update only. In elixir the shorthand for upsert is removed to reduce confusion. So this is also a good example to showcase the difference two languages’ philosophy: Erlang favors logic and completeness, Elixir favors ergonomics and sane default.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
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
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
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 43657 311
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29703 241
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
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
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement