[erlang-questions] Getting rid of some repetition.
Kenneth Lundin
kenneth.lundin@REDACTED
Tue Mar 18 14:55:24 CET 2008
On 3/18/08, Mats Cronqvist <mats.cronqvist@REDACTED> wrote:
> Colin Z wrote:
> > Say I have a process loop with a receive block that receives a bunch
> > of different messages...typical scenario:
> >
> > loop(A, B, C)->
> > receive
> > {msg1, A1}->
> > loop(A1, B, C)
> > ;
> > {msg2, B1}->
> > loop(A, B1, C)
> > ;
> > {msg3, C1}->
> > loop(A, B, C1)
> > ;
> > {msg4, A2, C2}->
> > loop(A2, B, C2)
> > end
> this idiom would reduce the typing;
>
> loop(A0, B0, C0)->
> receive
> {msg1, A1}-> B1=B0,C1=C0;
> {msg2, B1}-> A1=A0,C1=C0;
> {msg3, C1}-> A1=A0,B1=B0;
> {msg4, A1, C1}-> B1=B0;
> end,
> loop(A1, B1, C1).
>
> the new syntax you propose is a bit too perly for my taste.
>
> mats
>
I think this is even better:
loop(A0, B0, C0)->
{A,B,C} =
receive
{msg1, A1}-> {A1,B0,C0};
{msg2, B1}-> {A0,B1,C0};
{msg3, C1}-> {A0,B0,C1};
{msg4, A1, C1}-> {A1,B0,C1};
end,
loop(A1, B1, C1).
Of course you could have called loop directly from the case alternatives
as in the original example, but if each alternative need to do
something more complicated I think this is clear and easy to
understand.
Mats example is actually more complicated in my view with all the ugly
B1=B0, ... stuff.
/Kenneth
More information about the erlang-questions
mailing list