Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active September 21, 2022 03:06
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save henrik/d482d41288d732f97f2d to your computer and use it in GitHub Desktop.
Save henrik/d482d41288d732f97f2d to your computer and use it in GitHub Desktop.
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
@Neophen
Copy link

Neophen commented Aug 17, 2020

Awesome the second example with provide the true is a nicer syntax! thank you Henrik

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