Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active September 21, 2022 03:06
Show Gist options
  • Select an option

  • Save henrik/d482d41288d732f97f2d to your computer and use it in GitHub Desktop.

Select an option

Save henrik/d482d41288d732f97f2d to your computer and use it in GitHub Desktop.

Revisions

  1. henrik revised this gist Sep 6, 2015. No changes.
  2. henrik revised this gist Sep 5, 2015. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions regex_case.exs
    Original file line number Diff line number Diff line change
    @@ -5,8 +5,9 @@ defmodule RegexCase do
    {:->, context, [[condition], result]}
    end

    # Base case of "true -> nil" if nothing matches.
    new_lines = new_lines ++ [{:->, [], [[true], nil]}]
    # Base case if nothing matches; "cond" complains otherwise.
    base_case = quote do: (true -> nil)
    new_lines = new_lines ++ base_case

    quote do
    cond do
  3. henrik revised this gist Sep 5, 2015. No changes.
  4. henrik revised this gist Sep 5, 2015. No changes.
  5. henrik created this gist Sep 5, 2015.
    31 changes: 31 additions & 0 deletions regex_case.exs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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 of "true -> nil" if nothing matches.
    new_lines = new_lines ++ [{:->, [], [[true], nil]}]

    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