Skip to content

Instantly share code, notes, and snippets.

@josefrichter
Created June 1, 2020 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josefrichter/49c09f0bb1d4088a62d9855784411793 to your computer and use it in GitHub Desktop.
Save josefrichter/49c09f0bb1d4088a62d9855784411793 to your computer and use it in GitHub Desktop.
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