4

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?

Roberto Aloi
  • 30,570
  • 21
  • 75
  • 112
Xiao Jia
  • 4,169
  • 2
  • 29
  • 47

2 Answers2

4

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?

Community
  • 1
  • 1
demeshchuk
  • 742
  • 4
  • 10
  • 2
    That Erlang doesn't have first-class patterns is the reason why we have the *match patterns* in `ETS` and in the tracing. Not elegant but necessary. – rvirding Sep 27 '12 at 20:24
1

As demeshchuk points out this is not the case.

There is however a proposal to add something similar to the language:

http://www.erlang.org/eeps/eep-0029.html

Whether or not this is a good idea is a completely different question...

Lii
  • 11,553
  • 8
  • 64
  • 88