Updating maps in Elixir
Immutable updates: every change to the score hands back a new map and leaves the original alone.
# Maps never mutate: every update hands back a new map.
score = %{player: "June", points: 40, streak: 2}
leveled = %{score | points: score.points + 10}
IO.inspect(leveled, label: "after | update")
bumped = Map.put(leveled, :streak, leveled.streak + 1)
IO.inspect(bumped, label: "after put")
IO.puts("the original still says #{score.points}")
How it works
%{score | points: ...}rewrites an existing key; it refuses keys the map does not have.Map.putsetsstreakfrom the previous value on the newest copy.- The last line proves
scorenever changed.
Keywords and builtins used here
IOMap
The run, in numbers
- Lines
- 10
- Characters to type
- 344
- Tokens
- 84
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 72 seconds.
Step 2 of 3 in Maps & structs, step 11 of 27 in Language basics.