Update Items in a Map
TL;DR
Check for usage with different arity.
The Elixir docs are really good. They are deep, though, and it’s always tricky when you’re in unfamiliar territory. I RTFM looking for a way to increment a map with a count, but all I saw was Map.update!/3.
update!(map, key, fun) View Source
update!(map(), key(), (value() -> value())) :: map()
A trailing bang (exclamation mark) signifies a function or macro where failure cases raise an exception. source
I don’t want to deal with freaking errors. I guess I have to make my own.
defp do_count(word, acc) do
if (Map.has_key?(acc, word)) do
%{acc | word => Map.get(acc, word) + 1}
else
Map.put(acc, word, 1)
end
end
That works just fine, but it wasn’t needed. I got scared off by the exception and didn’t scroll down. Literally the next part showed how to do a similar thing but allows adding an initial value for missing keys.
update(map, key, initial, fun) View Source
update(map(), key(), value(), (value() -> value())) :: map()
That’s Better
defp do_count(word, acc) do
- if (Map.has_key?(acc, word)) do
- %{acc | word => Map.get(acc, word) + 1}
- else
- Map.put(acc, word, 1)
- end
+ Map.update(acc, word, 1, &(&1 + 1))
end