O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required