Created
June 1, 2020 20:25
-
-
Save josefrichter/49c09f0bb1d4088a62d9855784411793 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 Stack do | |
use GenServer | |
# Client | |
def start_link(default) when is_list(default) do | |
GenServer.start_link(__MODULE__, default) | |
end | |
def push(pid, element) do | |
GenServer.cast(pid, {:push, element}) | |
end | |
def pop(pid) do | |
GenServer.call(pid, :pop) | |
end | |
# Server (callbacks) | |
@impl true | |
def init(stack) do | |
{:ok, stack} | |
end | |
@impl true | |
def handle_call(:pop, _from, [head | tail]) do | |
{:reply, head, tail} | |
end | |
@impl true | |
def handle_cast({:push, element}, state) do | |
{:noreply, [element | state]} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment