Recently I have started spending some of my time with Elixir and following Dave Thomas’ Programming Elixir. Though I am half way through with the book, and still don’t have a very good hold on the language. After reading about processes in Elixir, I thought to write something my own so I wrote a small ping-pong program
defmodule PingPong do import :timer @timer 500 def ping(x) do receive do {pong_pid, n} when n <= x -> IO.puts ("Ping #{n}") send pong_pid, { self, (n) } sleep @timer ping(x) end end def pong(x) do receive do {ping_pid, n} when n <= x -> IO.puts ("Pong #{n}") send ping_pid, {self, (n + 1) } pong(x) end end def run(n) do {ping_pid, _} = spawn_monitor(PingPong, :ping, [n]) {pong_pid, _} = spawn_monitor(PingPong, :pong, [n]) send ping_pid, {pong_pid, 1} receive do msg -> IO.puts "Message received: #{msg}" end end end PingPong.run(30)
I am pretty sure that there would be much scope of improvement, but this is what I could write as of now. Your comments/suggestions are welcome, kindly add them in comments