Skip to content

Instantly share code, notes, and snippets.

@tallakt
Created March 3, 2016 13:59
Show Gist options
  • Save tallakt/a6701b1e5c2808c85104 to your computer and use it in GitHub Desktop.
Save tallakt/a6701b1e5c2808c85104 to your computer and use it in GitHub Desktop.
defmodule MatchAndAssign do
defmacro __using__(_) do
quote do
require MatchAndAssign
import MatchAndAssign, only: [match_and_assign: 2]
end
end
defp unhygienize(pattern = {n, _meta, c}) when is_atom(n) and is_atom(c) do
var! pattern
end
defp unhygienize({n, meta, l}) when is_atom(n) and is_list(l) do
{n, meta, Enum.map(l, &unhygienize/1)}
end
defp unhygienize(tuple) when is_tuple(tuple) do
tuple
|> Tuple.to_list
|> Enum.map(&unhygienize/1)
|> List.to_tuple
end
defp unhygienize(list) when is_list(list) do
Enum.map(list, &unhygienize/1)
end
defp unhygienize(other), do: other
defmacro match_and_assign(val, pattern) do
quote do
unquote(unhygienize(pattern)) = unquote(val)
end
end
end
defmodule A do
use MatchAndAssign
def test do
%{a: 1, b: 2}
|> match_and_assign(y = %{a: x})
IO.inspect x
IO.inspect y
end
end
A.test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment