How do we deal with complex structures when we want to assign items at different levels inside the structure? (Lets skip if this muddies the intent of the code or not and just deal with how it can be done ;) )
# Build up a map
m = %{ r: %{foo: "foo", bar: "bar", baz: %{qux: "qiz wiz"}}}
# Build up a map
m = % r: %WebAccount
Given the map m
how can I assign a variable f
to the key foo:
and a variable top
to the inner map containing foo:
and bar:
Turns out that the assignment can take place inside the pattern match
iex> %{r: top = %{foo: f}} = m
iex> top
%{bar: "bar", baz: %{qux: "qiz wiz"}, foo: "foo"}
iex> f
"foo"
iex> %{ r: top= %{baz: b=%{qux: q}}} = m
iex> q
"qiz wiz"
# What should `b` return?
For accessing nested structures when a pattern match is not required, check out Elixir's support for dynamic access.
If you have a complex strucuture that people will need to reach into to update or querry