Updating a Map

In the previous chapter we saw how lists are updated through a combination of copying and changing the head.

With maps, we can add new key/value entries and update existing entries without traversing the whole structure. But as with all values in Elixir, a map is immutable, and so the result of the update is a new map.

The simplest way to update a map is with this syntax:

 
new_map = %{ old_map | key => value, … }

This creates a new map that is a copy of the old, but the values associated with the keys on the right of the pipe character are updated:

 
iex>​ m = %{ a: 1, b: 2, c: 3 }
 
%{a: 1, b: 2, c: 3}​​
 
iex>​ m1 = %{ m | b: ​"two"​, c: ​"three"​ }
 
%{a: 1, b: ​"two"​, c: ​"three"​}​​
 
iex>​ m2 = %{ m1 | a: ​"one"​ }
 
%{a: ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.