Erlang basics · Lesson 11 (open contents)
Read and update nested maps
Use map patterns, `maps:get/2`, and immutable map updates.
Run this first
Run it once, change one input, and compare the new result.
%% Rebuild each changed map layer
Student = #{profile => #{name => <<"Maya">>, age => 12}},
Profile = maps:get(profile, Student),
Older = Student#{profile := Profile#{age := 13}},
{maps:get(age, Profile), maps:get(age, maps:get(profile, Older))}.- The result is
{12,13};Studentstill contains age 12.
Read from the first line down
- Read
maps:get(Key, Map): Read one key from a map. - Read
#{key := Value}: Update an existing map key. - Read
#{key => Value}: Add or replace a key.
Symbols are not secret signs
maps:get(Key, Map)Read one key from a map.
#{key := Value}Update an existing map key.
#{key => Value}Add or replace a key.
Match each name to its meaning
map access
maps:get/2 reads a known key and raises when it is missing.
map update
Map#{key := value} updates an existing key and returns a new map.
nested update
Read the inner map, update it, then place that new map into the outer map.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
maps:get/2 reads a known key and raises when it is missing.
Map#{key := value} updates an existing key and returns a new map.
Close the answer and try
Change a nested page count from 80 to 100.
Book = #{info => #{pages => 80}},
Info = maps:get(info, Book),
Longer = Book#{info := Info#{pages := ____}},
{maps:get(pages, Info), maps:get(pages, maps:get(info, Longer))}.Target result: Return {80,100}.
Stuck? Read one hint
Use 100 as the new page value.
After you run it, see one answer
Book = #{info => #{pages => 80}},
Info = maps:get(info, Book),
Longer = Book#{info := Info#{pages := 100}},
{maps:get(pages, Info), maps:get(pages, maps:get(info, Longer))}.Think about it: Does a map update change the old map?
No. It returns a new map and keeps the old value available.
Remember these three lines
- 1
Read known keys deliberately.
- 2
Use
:=to require an existing key. - 3
Rebuild nested layers from the inside out.