typestar

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

  1. %{score | points: ...} rewrites an existing key; it refuses keys the map does not have.
  2. Map.put sets streak from the previous value on the newest copy.
  3. The last line proves score never changed.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Maps & structs, step 11 of 27 in Language basics.

← Previous Next →