[erlang-questions] How to abstract out common receive clauses?

Ladislav Lenart <>
Fri May 6 11:57:36 CEST 2011


Hello.

I think something like this should work (not tested however!):

process(This, That, X) ->
   receive
     {From, do1} when X == a; X == b ->
       do1,
       process(This, That, X);
     {From, do2} when X == a; X == b ->
       do2,
       process(This, That, X);
     {From, do3} when X == a ->
       do3,
       process(This, That, X);
     {From, do4} when X == b ->
       do4,
       process(This, That, X)
   end.

In addition, you can also define helper macros like:

-define(is_a_or_b(X), X == a; X == b).
-define(is_a(X), X == a).
-define(is_b(X), X == b).

and rewrite the above using them.


HTH,

Ladislav Lenart


On 6.5.2011 11:31, Ivan Uemlianin wrote:
> Dear All
>
> % I have a process running continuously in a receive loop. It should act slightly differently depending on one of its state parameters. At the moment I have it like this:
>
> process(This, That, a) ->
> receive
> {From, do1} ->
> do1,
> process(This, That, a);
> {From, do2} ->
> do2,
> process(This, That, a);
> {From, do3} ->
> do3,
> process(This, That, a)
> end;
>
> process(This, That, b) ->
> receive
> {From, do1} ->
> do1,
> process(This, That, b);
> {From, do2} ->
> do2,
> process(This, That, b);
> {From, do4} ->
> do4,
> process(This, That, b)
> end.
>
>
> % Most of the receive clauses are common to both versions of process/3 (the real code is more complicated). Is there a way to abstract out the common parts? An "object oriented" language might use
> inheritance. Prolog might use backtracking, perhaps a bit like this:
>
> iProcess(This, That, a) ->
> receive
> {From, do3} ->
> do3,
> iProcess(This, That, a)
> end;
>
> iProcess(This, That, b) ->
> receive
> {From, do4} ->
> do4,
> iProcess(This, That, b)
> end;
>
> iProcess(This, That, Other) ->
> receive
> {From, do1} ->
> do1,
> iProcess(This, That, Other);
> {From, do2} ->
> do2,
> iProcess(This, That, Other)
> end.
>
>
> % A case would perhaps work, with the proviso that 'generic' receives would be evaluated first:
>
> cProcess(This, That, Other) ->
> receive
> {From, do1} ->
> do1,
> cProcess(This, That, Other);
> {From, do2} ->
> do2,
> cProcess(This, That, Other)
> end,
> case Other of
> a ->
> receive
> {From, do3} ->
> do3,
> cProcess(This, That, Other)
> end;
> b ->
> receive
> {From, do4} ->
> do4,
> cProcess(This, That, Other)
> end
> end.
>
>
> % Is there a canonical way of dealing with this problem (other than copy-and-paste)?
>
> With thanks and best wishes
>
> Ivan
>





More information about the erlang-questions mailing list