Instantly share code, notes, and snippets.

Embed
What would you like to do?
Proof-of-concept of an Elixir construct like `case` but that matches strings against regexps. #elixirlang
defmodule RegexCase do
defmacro regex_case(string, do: lines) do
new_lines = Enum.map lines, fn ({:->, context, [[regex], result]}) ->
condition = quote do: String.match?(unquote(string), unquote(regex))
{:->, context, [[condition], result]}
end
# Base case if nothing matches; "cond" complains otherwise.
base_case = quote do: (true -> nil)
new_lines = new_lines ++ base_case
quote do
cond do
unquote(new_lines)
end
end
end
end
defmodule Run do
import RegexCase
def run do
regex_case "hello" do
~r/x/ -> IO.puts("matches x")
~r/e/ -> IO.puts("matches e")
~r/y/ -> IO.puts("matches y")
end
end
end
Run.run
@henrik

This comment has been minimized.

Show comment
Hide comment
@henrik

henrik Feb 22, 2018

License: Public domain. No attribution needed.

Owner

henrik commented Feb 22, 2018

License: Public domain. No attribution needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment