Skip to content

Instantly share code, notes, and snippets.

@vic
Created December 22, 2016 18:38
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 vic/7961ef74cc7224ae7e1fdc14ddd575a0 to your computer and use it in GitHub Desktop.
Save vic/7961ef74cc7224ae7e1fdc14ddd575a0 to your computer and use it in GitHub Desktop.
defmodule DefGuard do
defp defguardp(defwith, name, meta = [{:when, _}, {:args, args} | _]) do
meta = meta |> Macro.escape
quote do
@expects {unquote(name), unquote(meta)}
unquote(defwith)(unquote(:"#{name}?")(unquote_splicing(args))) do
values = unquote(args |> Enum.map(fn value = {name, _, nil} -> {name, value} end))
unquote(meta[:when]) |> Macro.prewalk(fn
{name, _, nil} -> Keyword.get(values, name)
exp -> exp
end)
end
end
end
defmacro defguard({:when, _, [{{:unquote, _, [name]}, _, args}, guard]}, options) when is_atom(name) do
defexpectp(:defmacro, name, [{:when, guard}, {:args, args} | options])
end
defmacro defguard({:when, _, [{name, _, args}, guard]}, options) do
defexpectp(:defmacro, name, [{:when, guard}, {:args, args} | options])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment