Skip to content

Instantly share code, notes, and snippets.

@gausby
Created November 17, 2015 17:20
Show Gist options
  • Save gausby/01b999a495d834d22722 to your computer and use it in GitHub Desktop.
Save gausby/01b999a495d834d22722 to your computer and use it in GitHub Desktop.
defmodule Counter do
def start_link do
Agent.start_link(fn -> 0 end)
end
def set(pid, value) do
Agent.update(pid, fn _ -> value end)
end
def increment(pid) do
Agent.get_and_update(pid, fn state ->
{state + 1, state + 1}
end)
end
def decrement(pid) do
Agent.get_and_update(pid, fn state ->
{state - 1, state - 1}
end)
end
end
{:ok, pid} = Counter.start_link
Counter.increment(pid)
Counter.increment(pid)
Counter.increment(pid)
Counter.set(pid, 5)
Counter.decrement(pid)
Counter.increment(pid)
Agent.get(pid, &(&1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment