Created
March 15, 2017 22:32
-
-
Save bongani-m/b6e63d01daa12e37ea588bbfa0debd39 to your computer and use it in GitHub Desktop.
Elixir Account
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 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