Last active
March 23, 2019 12:37
-
-
Save Enforcer/fc654af591fb7aedd7824d04a45270c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule StackAgent do | |
use Agent | |
def start(initial_value) do | |
Agent.start(fn -> initial_value end, name: __MODULE__) | |
end | |
def value() do | |
Agent.get(__MODULE__, fn state -> state end) | |
end | |
def set_value(value) do | |
Agent.update(__MODULE__, fn _ -> value end) | |
end | |
end | |
defmodule Stack do | |
use GenServer | |
def init(init_arg) do | |
state = case StackAgent.start(init_arg) do | |
{:ok, agent_pid} -> | |
init_arg | |
{:error, {:already_started, agent_pid}} -> | |
StackAgent.value() | |
end | |
{:ok, state} | |
end | |
def pop(pid), do: GenServer.call(pid, :pop) | |
def push(pid, value), do: GenServer.cast(pid, {:push, value}) | |
def handle_call(:pop, _from, state) do | |
[head | tail] = state | |
StackAgent.set_value(tail) | |
{:reply, head, tail} | |
end | |
def handle_cast({:push, value}, state) do | |
StackAgent.set_value([value | state]) | |
{:noreply, [value | state]} | |
end | |
end | |
{:ok, pid} = GenServer.start_link(Stack, []) | |
IO.puts(Stack.push(pid, 1)) | |
IO.puts(Stack.pop(pid)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment