Skip to content

Instantly share code, notes, and snippets.

@danielberkompas
Created October 31, 2016 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielberkompas/b857f02c0fc8b9ef655e0181bef78daa to your computer and use it in GitHub Desktop.
Save danielberkompas/b857f02c0fc8b9ef655e0181bef78daa to your computer and use it in GitHub Desktop.
Javascript-style Destructuring for Elixir
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