Last active
December 1, 2021 13:31
-
-
Save hassanRsiddiqi/1b5d11c3ffe779bff1524911fffd222a to your computer and use it in GitHub Desktop.
This snippet is for learning Process in Elixir, with this snippet you can calculator basic arithmetic operation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Cal do | |
def start do | |
spawn(fn -> loop(0) end) | |
end | |
def view(server_pid) do | |
send(server_pid, {:view, self()}) | |
receive do | |
{:response, value} -> | |
value | |
end | |
end | |
def add(server_pid, value) do | |
send(server_pid, {:add, value}) | |
view(server_pid) | |
end | |
def sub(server_pid, value) do | |
send(server_pid, {:sub, value}) | |
view(server_pid) | |
end | |
def mult(server_pid, value) do | |
send(server_pid, {:mult, value}) | |
view(server_pid) | |
end | |
def div(server_pid, value) do | |
send(server_pid, {:div, value}) | |
view(server_pid) | |
end | |
defp loop(current_value) do | |
new_value = | |
receive do | |
{:view, caller_pid} -> | |
send(caller_pid, {:response, current_value}) | |
current_value | |
{:add, value} -> | |
current_value + value | |
{:sub, value} -> | |
current_value - value | |
{:mult, value} -> | |
current_value * value | |
{:div, value} -> | |
current_value / value | |
_ -> | |
IO.puts("Invalid Message") | |
end | |
loop(new_value) | |
end | |
end | |
# p = Cal.start | |
# Cal.add(p, 5) // 5 | |
# Cal.mult(p, 5) // 25 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment