mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Updating Values In A Map as an elixir til
This commit is contained in:
@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
|
||||
warrant a full blog post. These are mostly things I learn by pairing with
|
||||
smart people at [Hashrocket](http://hashrocket.com/).
|
||||
|
||||
_458 TILs and counting..._
|
||||
_459 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -94,6 +94,7 @@ _458 TILs and counting..._
|
||||
- [Replace Duplicates In A Keyword List](elixir/replace-duplicates-in-a-keyword-list.md)
|
||||
- [Reversing A List](elixir/reversing-a-list.md)
|
||||
- [String Interpolation With Just About Anything](elixir/string-interpolation-with-just-about-anything.md)
|
||||
- [Updating Values In A Map](elixir/updating-values-in-a-map.md)
|
||||
- [Word Lists For Atoms](elixir/word-lists-for-atoms.md)
|
||||
|
||||
### Git
|
||||
|
||||
41
elixir/updating-values-in-a-map.md
Normal file
41
elixir/updating-values-in-a-map.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# 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 update, and a
|
||||
function for _transforming_ (or updating) the existing value.
|
||||
|
||||
Let's use a score counting example to see it in action:
|
||||
|
||||
```elixir
|
||||
> scores = %{}
|
||||
%{}
|
||||
# jake scores a point
|
||||
> {_, scores} = Map.get_and_update(scores, :jake, fn(x) -> {x, (x || 0) + 1} end)
|
||||
{nil, %{jake: 1}}
|
||||
# chris scores a point
|
||||
> {_, scores} = Map.get_and_update(scores, :chris, fn(x) -> {x, (x || 0) + 1} end)
|
||||
{nil, %{chris: 1, jake: 1}}
|
||||
# jake scores another point
|
||||
> {_, scores} = Map.get_and_update(scores, :jake, fn(x) -> {x, (x || 0) + 1} end)
|
||||
{1, %{chris: 1, jake: 2}}
|
||||
# final scores
|
||||
> scores
|
||||
%{chris: 1, jake: 2}
|
||||
```
|
||||
|
||||
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](http://elixir-lang.org/docs/stable/elixir/Map.html#get_and_update/3)
|
||||
for more details.
|
||||
Reference in New Issue
Block a user