Created
January 24, 2023 09:41
-
-
Save vKxni/c45e1b6fabeef119f72c69106618e128 to your computer and use it in GitHub Desktop.
Macro matching
This file contains 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 MyMacros do | |
defmacro match(values) do | |
quoted_values = Enum.map(values, "e(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