Skip to content

Instantly share code, notes, and snippets.

@JohnB
Last active October 22, 2017 20:32
Show Gist options
  • Save JohnB/4e224846aaaa8fa76cf4fed76a97a5b6 to your computer and use it in GitHub Desktop.
Save JohnB/4e224846aaaa8fa76cf4fed76a97a5b6 to your computer and use it in GitHub Desktop.
Object-oriented version of the canonical stack example.
defmodule Stack do
use GenServer
# Public Interface (runs in the caller's process)
def create() do
{:ok, pid} = GenServer.start_link(__MODULE__, [])
pid
end
def push(pid, item) do
GenServer.cast(pid, {:push, item})
end
def pop(pid) do
GenServer.call(pid, :pop)
end
def clear(pid) do
GenServer.cast(pid, :clear)
end
def empty?(pid) do
GenServer.call(pid, :empty?)
end
# Semi-private API to the object's process entry points.
# Accessible to all elixir nodes but a kind of syntactic vinegar - at least
# when compared to the syntactic sugar of the public interface above.
def handle_cast({:push, item}, state) do
{:noreply, [item | state]}
end
def handle_cast(:clear, _state) do
{:noreply, []}
end
def handle_call(:pop, _from, []) do
{:reply, nil, []}
end
def handle_call(:pop, _from, [h | t]) do
{:reply, h, t}
end
def handle_call(:empty?, _from, state) do
{:reply, Enum.empty?(state), state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment