[erlang-questions] Pass a pattern to a function

Ladislav Lenart <>
Tue Feb 10 20:31:41 CET 2009


Jachym Holecek wrote:
> Hello,
> 
> # Sten Gruener 2009-02-10:
>> I try to write a function to scan the message queue and discard matched
>> messages.
>>
>> Like this:
>>
>> discard(Pattern) ->
>>     receive
>>         Pattern ->
>>             discard(Pattern)
>>     after 0 ->
>>         ok
>>     end.
>>
>> the problem is, that I cannot call discard({_, {msg}}) since _ is a wildcard
>> representation. Are there any solutions?
> 
> Patterns aren't first class objects so I'm afraid you're SOL. You could
> implement your discard/1 as a parse transform, but under the hood that
> would just create per-pattern-specialised discard functions. Alternatively,
> it would be doable with a macro, but I can't imagine that not being ugly.

Hello,

the suggested macro solution, if applicable to your needs,
is not that ugly actually (the code below is not tested)...

%% Definition:
-define(discard(Pattern),
  fun () ->
      F = fun (G) ->
              receive
                  Pattern ->
                      G(G)
              after 0 ->
                  ok
              end
           end,
       F(F),
  end()).

%% Usage:
?discard({_, X}),


HTH,

Ladislav Lenart





More information about the erlang-questions mailing list