Skip to content

Instantly share code, notes, and snippets.

@bongani-m
Created March 15, 2017 22:32
Show Gist options
  • Save bongani-m/b6e63d01daa12e37ea588bbfa0debd39 to your computer and use it in GitHub Desktop.
Save bongani-m/b6e63d01daa12e37ea588bbfa0debd39 to your computer and use it in GitHub Desktop.
Elixir Account
defmodule Account do
def new(balance \\ 0) do
fun = fn -> loop(balance) end
spawn(fun)
end
def deposit(account, amount) do
send(account, {:deposit, amount})
end
def withdraw(account, amount) do
send(account, {:withdraw, amount})
end
def balance(account) do
send(account, {:balance, self()})
receive do
{:balance, content} -> {:balance, content}
end
end
def loop(balance) do
receive do
{:deposit, amount} ->
loop(balance + amount)
{:withdraw, amount} ->
new_balance = if ( balance - amount > 0), do: balance - amount, else: balance - amount - 32
loop(new_balance)
{:balance, parent} ->
send(parent, {:balance, balance})
loop(balance)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment