Skip to content

Instantly share code, notes, and snippets.

@oklaiss
Created September 28, 2016 21:47
Show Gist options
  • Save oklaiss/fd5cb2ece57e4ab90ea36ef6f37e705a to your computer and use it in GitHub Desktop.
Save oklaiss/fd5cb2ece57e4ab90ea36ef6f37e705a to your computer and use it in GitHub Desktop.
Elixir Agents
defmodule OA do
#######
# API #
#######
def new do
{ :ok, agent } = Agent.start_link(fn -> %{ location_of: %{} } end)
agent
end
def enter_building(agent, person) do
Agent.get_and_update(agent, __MODULE__, :record_entry, [ person ])
end
def leave_building(agent, person) do
Agent.get_and_update(agent, __MODULE__, :record_exit, [ person ])
end
def who_is_where(agent) do
Agent.get(agent, &(&1.location_of))
end
##################
# Implementation #
##################
def record_entry(state, person) do
current_place = state.location_of[person]
maybe_enter(current_place, state, person)
end
defp maybe_enter(:in_building, state, person) do
{ { :in_building_twice, person }, state }
end
defp maybe_enter(_, state, person) do
state = put_in(state, [:location_of, person], :in_building)
{ { :ok, person }, state }
end
def record_exit(state, person) do
current_place = state.location_of[person]
maybe_leave(current_place, state, person)
end
defp maybe_leave(:in_building, state, person) do
state = put_in(state, [:location_of, person], :not_in_building)
{ { :ok, person }, state }
end
defp maybe_leave(_, state, person) do
{ { :not_in_building, person }, state }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment