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
{bill, From, Minutes}carries the return address.- The worker answers
From ! {billed, ...}and loops. - The caller's receive matches only the expected reply.
Keywords and builtins used here
beginbillerendformatfunmainreceivespawn
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.
Step 3 of 4 in Processes, step 27 of 31 in Language basics.