Skip to content

Instantly share code, notes, and snippets.

@vKxni
Created January 24, 2023 09:41
Show Gist options
  • Save vKxni/c45e1b6fabeef119f72c69106618e128 to your computer and use it in GitHub Desktop.
Save vKxni/c45e1b6fabeef119f72c69106618e128 to your computer and use it in GitHub Desktop.
Macro matching
defmodule MyMacros do
defmacro match(values) do
quoted_values = Enum.map(values, &quote(unquote(&1)))
quote do
def match(x) do
case x do
#{unquote(quoted_values)} -> true
_ -> false
end
end
end
end
end
# yes
defmodule MyModule do
import MyMacros
match([:a, :b, :c])
end
MyModule.match(:a) # => true
MyModule.match(:d) # => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment