[erlang-questions] Getting rid of some repetition.

Mats Cronqvist mats.cronqvist@REDACTED
Tue Mar 18 20:24:15 CET 2008


Kenneth Lundin wrote:
> 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
>>
>>
>>     
> [...]
>
> Mats example is actually more complicated in my view with all the ugly
> B1=B0, ... stuff.
>   
  at least it compiled :>
  just for completeness, here's The Correct Solution (tm) (*);

-record(rec,{a,b,c}).
loop(Rec) ->
  receive
    Msg -> loop(update_rec(Rec,Msg))
  end.
update_rec(Rec,{msg1, A})  -> Rec#rec{a=A};
update_rec(Rec,{msg2, B}   -> Rec#rec{b=B};
update_rec(Rec,{msg3, C}   -> Rec#rec{c=C};
update_rec(Rec,{msg4, A, C}-> Rec#rec{a=A,c=C}.

  mats

p.s.  gen_server is an even more correct solution.

(*) might not compile, i've only proved it correct.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: mats_cronqvist.vcf
Type: text/x-vcard
Size: 179 bytes
Desc: not available
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20080318/d9446472/attachment.vcf>


More information about the erlang-questions mailing list