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

Ivan Uemlianin ivan@REDACTED
Fri May 6 11:31:04 CEST 2011


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

-- 
============================================================
Ivan A. Uemlianin
Speech Technology Research and Development

                     ivan@REDACTED
                      www.llaisdy.com
                          llaisdy.wordpress.com
                      www.linkedin.com/in/ivanuemlianin

     "Froh, froh! Wie seine Sonnen, seine Sonnen fliegen"
                      (Schiller, Beethoven)
============================================================




More information about the erlang-questions mailing list