Skip to content

Instantly share code, notes, and snippets.

@daksis
Last active April 9, 2018 13:11
Show Gist options
  • Save daksis/2a82c2c44221d4fbe4fc3d84fc91361f to your computer and use it in GitHub Desktop.
Save daksis/2a82c2c44221d4fbe4fc3d84fc91361f to your computer and use it in GitHub Desktop.
Elixir: matching on deeply nested maps

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment