[erlang-questions] Pass a pattern to a function

Richard O'Keefe ok@REDACTED
Wed Feb 11 02:00:56 CET 2009


On 11 Feb 2009, at 6:08 am, Sten Gruener wrote:

> Hello,
>
> 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 are not values in Erlang.
It's not just wildcards that get in the way.

It sounds very much as though you want to do
	Message_Queue := filter(fun (Pattern) -> false; (_) -> true end,
				Message_Queue)
except that you can't do that either.

What you *can* do is write a macro that constructs a recursive function.

	-define(DISCARD(Pat),
	    (F = fun (G) ->
		    receive Pat -> G(G)
		      after 0   -> ok
		    end
		 end,
              F(F)
	    )).

I haven't tried this, and I avoid macros when I can, so expect
to have to debug it.  If I've got this right, then
	?DISCARD({_, {msg}})
should do the trick.

Having said that, I would urge you to restructure your program
so that this no longer seems useful to you.  Instead of letting
the messages build up in the queue and purging them later, try
to structure the program so that they never enter the queue in
the first place (perhaps by arranging for the messages to be
sent to an intermediate filtering process) or that catches them
earlier.





More information about the erlang-questions mailing list