typestar

Call and reply in Erlang

Tag requests with self(); match the reply by shape.

%% The call-and-reply shape: tag requests with self(), match replies.
biller() ->
    receive
        {bill, From, Minutes} ->
            From ! {billed, Minutes * 4},
            biller();
        stop -> ok
    end.

main(_) ->
    Pid = spawn(fun biller/0),
    [begin
         Pid ! {bill, self(), M},
         receive {billed, Pence} ->
             io:format("~p min -> ~p pence~n", [M, Pence])
         end
     end || M <- [3, 12, 7]],
    Pid ! stop.

How it works

  1. {bill, From, Minutes} carries the return address.
  2. The worker answers From ! {billed, ...} and loops.
  3. The caller's receive matches only the expected reply.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
355
Tokens
112
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 122 seconds.

Type this snippet

Step 3 of 4 in Processes, step 27 of 31 in Language basics.

← Previous Next →