So I’ve started learning Erlang and I’m a little confused with this chunk of code.
-module(prior).
-compile(export_all).
important() ->
receive
{ Priority, Msg } when Priority > 10 ->
[Msg | important()]
after 0 ->
normal()
end.
normal() ->
receive
{ _, Msg } ->
[Msg | normal()]
after 0 ->
[]
end.
I am calling the code using.
10> self() ! {15, high}, self() ! {7, low}, self() ! {1, low}, self() ! {17, high}.
{17,high}
11> prior:important().
[high,high,low,low]
I understand that this code will go through all the high priority messages first and then the low priority ones. I’m confused as to how the return value is[high,high,low,low], since I don’t see where they are concatenated together.
How the final return value is constructed…
When
[Msg | important()]is being returned for the first time, the form of the final return value is determined. The only concern is, we don’t know all the details of the final return value yet. So theimportant()in the[Msg | important()]will continue being evaluated. The following is an illustration of how the final return value[high,high,low,low]is constructed.How the code works…
In function
important/0,after 0simply means “I don’t wait for messages to come” — if there is any message in my mailbox, I will look at it; if there isn’t any, I will keep going (executenormal()) rather than waiting there. In the mailbox, there are {15, high}, {7, low}, {1, low}, {17, high} sitting there already. In Erlang, the messages in the mailbox are Not queued in a first-come-first-serve order. Thereceiveclause can be picky. It scans through all the messages in the mailbox and “picks” the ones it desires. In our case, {15, high} and {17, high} get picked first according to{Priority, Msg} when Priority > 10.After that, the function
normal/0takes over. And {7, low}, {1, low} get processed (consed) in order. Finally, we got[high,high,low,low].A modified version that reveals the processing order…
We can modify the code a little bit in order to make the processing (consing) order more explicit:
Run it in the shell: