Skip to content

Instantly share code, notes, and snippets.

@thijsnado
Last active December 19, 2015 17:19
Show Gist options
  • Save thijsnado/5990767 to your computer and use it in GitHub Desktop.
Save thijsnado/5990767 to your computer and use it in GitHub Desktop.
Suck it immutable state!
defrecord Mutant, pid: nil, _first_name: nil do
def init do
pid = spawn(Mutant, :run, [])
current_state(pid)
end
def current_state(pid) do
pid <- {self, :state }
receive do
{ :ok, record } -> record
end
end
def run do
record = Mutant.new(pid: self)
run(record)
end
def run(record) do
receive do
{ sender, :state } ->
sender <- { :ok, record }
run(record)
{ sender, :state, new_record } ->
sender <- :ok
run(new_record)
end
end
def first_name(record) do
real_record = current_state(record.pid)
real_record._first_name
end
def set_first_name(name, record) do
record.pid <- { self, :state, record._first_name(name) }
end
end
record = Mutant.init
record.set_first_name("bob")
IO.puts record.first_name
IO.puts record.first_name
record.set_first_name("Joe")
IO.puts record.first_name
IO.puts record.first_name
record.set_first_name("Thijs")
IO.puts record.first_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment