Skip to content

Instantly share code, notes, and snippets.

@yowchun93
Last active January 20, 2019 09:27
Show Gist options
  • Save yowchun93/4c36ee437ee5bf99029c7c509b932b07 to your computer and use it in GitHub Desktop.
Save yowchun93/4c36ee437ee5bf99029c7c509b932b07 to your computer and use it in GitHub Desktop.
Simple Elixir Calculator Server
defmodule Calculator do
def start do
spawn( fn -> loop(0) end)
end
defp loop(current_value) do
new_value = receive do
{sender_pid, :value} ->
IO.puts("current value is #{current_value}")
current_value
{sender_pid, :add, value} ->
#send(sender_pid,{:new_value, current_value + value})
current_value + value
{sender_pid, :deduct, value} ->
#send(sender_pid,{:new_value, current_value - value})
current_value - value
{sender_pid, :multiply, value} ->
#send(sender_pid,{:new_value, current_value * value})
current_value * value
end
loop(new_value)
end
end
# Refactored Version
defmodule Calculator do
def start do
spawn( fn -> loop(0) end)
end
defp loop(current_value) do
new_value = receive do
message ->
process_message(current_value, message)
end
loop(new_value)
end
def process_message(current_value, {:value}) do
IO.puts("current value is #{current_value}")
current_value
end
def process_message(current_value, {:add, value}) do
current_value + value
end
def process_message(current_value, {:deduct, value}) do
current_value - value
end
def process_message(current_value, {:multiply, value}) do
current_value * value
end
def process_message(current_value, {:divide, value}) do
current_value / value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment