2
votes

Lets say I have a module I'm making where pattern matching is the bulk of it's functionality, like a struct or fancy case statement; is there a way that use Module can insert a clause at the bottom of the Module its used on? The reason for this is to add, lets say, default clauses that would catch matches which fail against those declared.

For a contrived example:

defmodule NumberToNumber do
    use SwitchLib, default: 0
#   import SomeMacros

    opt 1, "one"
#   convert("one"), do: 1

    opt 2, "two"
    opt 3, "three"
    opt 4, "four"

    default 0            <-- Can this be procedurally generated?
#   convert(_), do: 0    <--     or this, for that matter,

end

Is this possible, or should I be going about this a different way? My back up plan is to quote in a convert(_) that attempts __MODULE__.convert(arg) itself and accounts for no match independently.

In any event, is the aforementioned method made possible by the compiler?

1

1 Answers

3
votes

Yes,

Callbacks such as @before_compile allow you to inject code into the module when its definition is complete.

Besides @before_compile there are other useful module attributes like @on_definition and @after_compile, which you can read more about in the docs for the Module module.

All of these facilities can be used in tandem with __using__ or vanilla macros to create dynamically generated code that permits for you to write a loop that creates opt i statements for arbitrary ranges of i. You can find useful information about macros and the compilation environment in the documentation for the Macro module and Macro.Env.