Search code examples
macroserlanglanguage-featuresfirst-class

First-class patterns in Erlang?


Are there any support for first-class patterns in Erlang?

f(SomeMagicPattern) ->
  receive
    SomeMagicPattern -> ok
  end.

If the answer is no (support), do you know any other approach for achieving this? For example, using macros?


Solution

  • No, Erlang doesn't have first-class patterns out of the box. There are two ways of implementing this:

    1. Macros. Widely used, for example in testing tools like EUnit and PropEr. Say, EUnit has an ?assertMatch macro, which is in fact an example of first-class patterns:

      ?assertMatch({ok, _}, Result)

    2. Parse transforms. Harder to write, but potentially more powerful, since using them you can access Erlang abstract code and rewrite it completely, in any way you desire. There's a nice link to a series of tutorials on parse transforms here: Is there a good, complete tutorial on Erlang parse transforms available?