Skip to content

Instantly share code, notes, and snippets.

@christhekeele
Last active January 2, 2016 12:59
Show Gist options
  • Save christhekeele/8306780 to your computer and use it in GitHub Desktop.
Save christhekeele/8306780 to your computer and use it in GitHub Desktop.
Macro for testings pattern and guards in iex.
# Put in your .iex, and `require Pattern`
defmodule Pattern do
defmacro match?(pattern, input, code_block // []) do
code = Dict.get(code_block, :do, nil)
quote do
case unquote(input) do
unquote(pattern) ->
unquote(code)
:ok
_ ->
:no_match
end
end
end
end
# Pattern.match? [1, x, y], [1, 2, 3]
#=> :ok
# Pattern.match? [1, x, y], [2, 2, 3]
#=> :no_match
# Pattern.match? [1, x, y], [1, 2, 3], do: x |> inspect |> IO.puts
#==> 2
#=> :ok
# Pattern.match? x when x < 10, 10, do: x |> inspect |> IO.puts
#=> :no_match
# Pattern.match? x when x >= 10, 10, do: x |> inspect |> IO.puts
#==> 10
#=> :ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment