Skip to content

Instantly share code, notes, and snippets.

@rehia
Last active June 7, 2024 18:01
Show Gist options
  • Select an option

  • Save rehia/98ee1c1f0bc2d7fa831f4818172fcc11 to your computer and use it in GitHub Desktop.

Select an option

Save rehia/98ee1c1f0bc2d7fa831f4818172fcc11 to your computer and use it in GitHub Desktop.
Exercism Elixir exercise on agents done at AlpesCraft 2024
defmodule Plot do
@enforce_keys [:plot_id, :registered_to]
defstruct [:plot_id, :registered_to]
end
defmodule State do
@enforce_keyz [:next_id, :registrations]
defstruct [:next_id, :registrations]
end
defmodule CommunityGarden do
def start() do
Agent.start(fn -> %State{next_id: 1, registrations: []} end)
end
def list_registrations(pid) do
Agent.get(pid, fn state -> state.registrations end)
end
def register(pid, register_to) do
Agent.get_and_update(pid, fn state -> register_in_state(state, register_to) end)
end
defp register_in_state(state, register_to) do
new_plot = %Plot{plot_id: state.next_id, registered_to: register_to}
{new_plot, %State{next_id: state.next_id + 1, registrations: state.registrations ++ [new_plot]}}
end
def release(pid, plot_id) do
Agent.update(pid, fn state ->
%State{
next_id: state.next_id,
registrations: Enum.filter(state.registrations, fn plot -> plot.plot_id != plot_id end) }
end)
end
def get_registration(pid, plot_id) do
Agent.get(pid, fn state -> Enum.find(state.registrations, {:not_found, "plot is unregistered"}, fn plot -> plot.plot_id == plot_id end) end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment