Updating Values In A Map
When working with maps in any language, you often need a way to update key-value pairs. Furthermore, you will need a way to handle keys that are not already present in the map, generally associating some default value.
In Elixir, the Map
module provides the get_and_update/3
function as a way of accomplishing such a task.
You need to provide the map, the key to be fetched and updated, and a function for transforming (or updating) the existing value.
Let's use a score counting example to see it in action:
We use (x || 0) + 1
as the updated value. This is a simple way of providing a default value for when the key is not already present in the map.
The update function is expected to return a tuple with the original value and the updated value.
See the docs for more details.
Last updated