Advertisement
Guest User

Untitled

a guest
Sep 29th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. defmodule OA do
  2.  
  3. #######
  4. # API #
  5. #######
  6.  
  7. def new do
  8. { :ok, agent } = Agent.start_link(fn -> %{ location_of: %{} } end)
  9. agent
  10. end
  11.  
  12. def enter_building(agent, person) do
  13. Agent.get_and_update(agent, __MODULE__, :record_entry, [ person ])
  14. end
  15.  
  16. def who_is_where(agent) do
  17. Agent.get(agent, &(&1.location_of))
  18. end
  19.  
  20. def leave_building(agent, person) do
  21. Agent.get_and_update(agent, __MODULE__, :record_exit, [ person ])
  22. end
  23.  
  24. ##################
  25. # Implementation #
  26. ##################
  27.  
  28. def record_entry(state, person) do
  29. current_place = state.location_of[person]
  30. maybe_enter(current_place, state, person)
  31. end
  32.  
  33. def record_exit(state, person) do
  34. current_place = state.location_of[person]
  35. maybe_exit(current_place, state, person)
  36. end
  37.  
  38. defp maybe_enter(:in_building, state, person) do
  39. { { :in_building_twice, person }, state }
  40. end
  41.  
  42. defp maybe_enter(_, state, person) do
  43. state = put_in(state, [:location_of, person], :in_building)
  44. { { :ok, person }, state }
  45. end
  46.  
  47. defp maybe_exit(:in_building, state, person) do
  48. state = put_in(state, [:location_of, person], :elsewhere)
  49. { { :ok, person }, state }
  50. end
  51.  
  52. defp maybe_exit(_, state, person) do
  53. { { :tried_to_exit_from_outside, person }, state }
  54. end
  55.  
  56. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement