Created
October 31, 2016 20:26
-
-
Save danielberkompas/b857f02c0fc8b9ef655e0181bef78daa to your computer and use it in GitHub Desktop.
Javascript-style Destructuring for Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Destructure do | |
@moduledoc """ | |
Provides helpers for destructuring Elixir data structures. See the `d/1` macro | |
for more information. | |
""" | |
@doc """ | |
Easy destructuring of maps and keyword lists, with atom keys only. | |
## Examples | |
The macro can be used in simple match statements: | |
iex> d(%{name}) = %{name: "Joe"} | |
...> name | |
"Joe" | |
Or in case/for/with statements. | |
iex> case %{name: "Mike"} do | |
...> d%{name} -> | |
...> name | |
...> end | |
"Mike" | |
It can be used inside a complex match: | |
iex> %{body: d%{name}} = %{body: %{name: "Robert"}} | |
...> name | |
"Robert" | |
For keyword lists: | |
iex> d({name}) = [name: "Daniel"] | |
...> name | |
"Daniel" | |
And in function definitions: | |
iex> defmodule Test do | |
...> import Destructure | |
...> def test(d%{name}) do | |
...> name | |
...> end | |
...> end | |
...> Test.test(%{name: "Daniel"}) | |
"Daniel" | |
""" | |
defmacro d({:%{}, context, [{key, _, _} = variable]}) do | |
{:%{}, context, [{key, variable}]} | |
end | |
defmacro d({:{}, _, [{key, _, _} = variable]}) do | |
[{key, variable}] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment