← Back to lesson 12: Read and update nested data

Read and update nested data: 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 keyword lists, maps, `get_in`, `put_in`, and `update_in` without changing the source value.

Update one nested age and prove that the original map still holds the old value.

Run this first

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

Original full example
# Update a nested map without changing student
student = %{profile: %{name: "Maya", age: 12}, options: [active: true]}
older = put_in(student.profile.age, 13)
{get_in(older, [:profile, :name]), student.profile.age, older.profile.age}

The result is {"Maya", 12, 13}; student remains unchanged.

Steps for the full example

  1. Read [active: true]: Write a keyword list.
  2. Read get_in(data, path): Read a value along a nested path.
  3. Read put_in(data.path, value): Return a copy with one nested value replaced.

Original lesson notes

Run the example first. Predict one result, then change one input and run it again.

A keyword list is a list of two-item tuples with atom keys; options often use this form.

get_in/2 follows a path through nested maps or keyword data.

Symbols and terms
[active: true]
Write a keyword list.
get_in(data, path)
Read a value along a nested path.
put_in(data.path, value)
Return a copy with one nested value replaced.
keyword list
A keyword list is a list of two-item tuples with atom keys; options often use this form.
nested access
get_in/2 follows a path through nested maps or keyword data.
immutable update
put_in and update_in return new data instead of editing the original value.

Original full exercise

Add 20 pages to a nested book map with update_in.

Exercise starter
book = %{info: %{title: "River", pages: 80}}
longer = update_in(book.info.pages, fn pages -> ____ end)
{book.info.pages, longer.info.pages}

Return {80, 100}.

Show hint

Return pages + 20 from the anonymous function.

Show original answer
Reference answer
book = %{info: %{title: "River", pages: 80}}
longer = update_in(book.info.pages, fn pages -> pages + 20 end)
{book.info.pages, longer.info.pages}
Does put_in edit its input map?

No. It returns a new value with the requested path changed.

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