Channel Directions in Erlang
In Erlang, we can demonstrate the concept of channel directions using processes and message passing. While Erlang doesn’t have channels in the same way as Go, we can achieve similar functionality using processes.
-module(channel_directions).
-export([start/0]).
% This ping function only sends a message to a process.
% It would be a runtime error to try to receive on this process.
ping(Pings, Msg) ->
Pings ! Msg.
% The pong function receives a message from one process
% and sends it to another.
pong(Pings, Pongs) ->
receive
Msg ->
Pongs ! Msg
end.
start() ->
Pings = spawn(fun() -> receive_loop() end),
Pongs = spawn(fun() -> receive_loop() end),
ping(Pings, "passed message"),
pong(Pings, Pongs),
receive_and_print(Pongs).
receive_loop() ->
receive
Msg ->
self() ! Msg,
receive_loop()
end.
receive_and_print(Pid) ->
receive
Msg ->
io:format("~p~n", [Msg])
after 1000 ->
io:format("No message received~n")
end.In this Erlang example, we use processes to simulate channel-like behavior:
The
pingfunction sends a message to a process.The
pongfunction receives a message from one process and sends it to another.In the
startfunction:- We spawn two processes to act as our “channels”.
- We call
pingto send a message to the first process. - We call
pongto receive from the first process and send to the second. - Finally, we receive and print the message from the second process.
To run the program:
$ erlc channel_directions.erl
$ erl -noshell -s channel_directions start -s init stop
passed messageThis example demonstrates how Erlang’s processes and message passing can be used to achieve functionality similar to Go’s channel directions. While the syntax and mechanisms are different, the concept of controlling the flow of data between concurrent entities remains the same.