← Back to lesson 11: Read and update nested maps

Read and update nested maps: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Use map patterns, `maps:get/2`, and immutable map updates.

Update one nested age and return both the original and new values.

Run this first

Run it once, change one input, and compare the new result.

Original full example
%% 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}; Student still contains age 12.

Steps for the full example

  1. Read maps:get(Key, Map): Read one key from a map.
  2. Read #{key := Value}: Update an existing map key.
  3. Read #{key => Value}: Add or replace a key.

Original lesson notes

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.

Symbols and terms
maps:get(Key, Map)
Read one key from a map.
#{key := Value}
Update an existing map key.
#{key => Value}
Add or replace a key.
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.

Original full exercise

Change a nested page count from 80 to 100.

Exercise starter
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))}.

Return {80,100}.

Show hint

Use 100 as the new page value.

Show original answer
Reference 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))}.
Does a map update change the old map?

No. It returns a new map and keeps the old value available.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references