Elixir basics · Lesson 11 (open contents)
Read and update nested data
Use keyword lists, maps, `get_in`, `put_in`, and `update_in` without changing the source value.
Run this first
Run it once, change one input, and compare the new result.
# 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};studentremains unchanged.
Read from the first line down
- Read
[active: true]: Write a keyword list. - Read
get_in(data, path): Read a value along a nested path. - Read
put_in(data.path, value): Return a copy with one nested value replaced.
Symbols are not secret signs
[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.
Match each name to its meaning
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.
Why these forms are useful
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.
Close the answer and try
Add 20 pages to a nested book map with update_in.
book = %{info: %{title: "River", pages: 80}}
longer = update_in(book.info.pages, fn pages -> ____ end)
{book.info.pages, longer.info.pages}Target result: Return {80, 100}.
Stuck? Read one hint
Return pages + 20 from the anonymous function.
After you run it, see one answer
book = %{info: %{title: "River", pages: 80}}
longer = update_in(book.info.pages, fn pages -> pages + 20 end)
{book.info.pages, longer.info.pages}Think about it: Does `put_in` edit its input map?
No. It returns a new value with the requested path changed.
Remember these three lines
- 1
Keyword lists commonly carry options.
- 2
Use paths to read nested data.
- 3
Updates return new collections.