[erlang-questions] Newbie help please with variable unsafe in 'receive' & variable unused

Richard A. O'Keefe <>
Fri Sep 30 04:24:31 CEST 2016



On 30/09/16 5:29 AM, Donald Steven wrote:
>
> loop(Orbiter1, Orbiter2, Orbiter3) ->
>
>     receive
>         {Orbiter1, Coordinates = {{X1, Y1, Z1}}} ->                 %
> the io:format statements are just fro debugging.  What I really need
>             io:format("Coordinates: ~p~n", [Coordinates]),            %
> are the X1, Y1, and Z1 coordinates so that I can do some work with them
>             io:format("X1: ~p, Y1: ~p, Z1: ~p~n", [X1, Y1, Z1]);    %
> beyond the end of the 'receive'
>         {Orbiter2, Coordinates = {{X2, Y2, Z2}}} ->
>             io:format("Coordinates: ~p~n", [Coordinates]),
>             io:format("X2: ~p, Y2: ~p, Z2: ~p~n", [X2, Y2, Z2]);
>         {Orbiter3, Coordinates = {{X3, Y3, Z3}}} ->
>             io:format("Coordinates: ~p~n", [Coordinates]),
>             io:format("X3: ~p, Y3: ~p, Z3: ~p~n", [X3, Y3, Z3]);
>         _ ->
>             ok % stop if unknown message arrives
>     end,
>
>     io:format("X1: ~p, Y1: ~p, Z1: ~p~n", [X1, Y1, Z1]),        % this
> would really be more substantial code.  This is a placeholder
>     loop(Orbiter1, Orbiter2, Orbiter3).

At your "placeholder" line, if an {Orbiter2, {{X2,Y2,Z2}}} message
arrived, what values do you expect X1,Y1,Z1 to have, and why do
you expect them to have those values?

I would suggest code like

loop(Orbiter1, Orbiter2, Orbiter3) ->
     receive
         {Orbiter1, {XYZ}} -> handle(1, Orbiter1, XYZ)
       ; {Orbiter2, {XYZ}} -> handle(2, Orbiter2, XYZ)
       ; {Orbiter3, {XYZ}} -> handle(3, Orbiter3, XYZ)
       ; _Other                  -> ignored
     end,
     loop(Orbiter1, Orbiter2, Orbiter3).

handle(Orbiter_Index, Orbiter, XYZ) ->
   % debugging
     io:format("Orbiter ~d coordinates = ~p~n",
         [Orbiter_Index, XYZ},
   % real work
     ok.



More information about the erlang-questions mailing list