Skip to content

Instantly share code, notes, and snippets.

@sofakingworld
Last active March 20, 2019 00:00
Show Gist options
  • Save sofakingworld/58c8e7903e7de05cf3cfc5d2a1cbce44 to your computer and use it in GitHub Desktop.
Save sofakingworld/58c8e7903e7de05cf3cfc5d2a1cbce44 to your computer and use it in GitHub Desktop.
Elixir Genserver#1
defmodule StackGenserver do
use GenServer
# Client
def start_link(default) when is_list(default) do
GenServer.start_link(__MODULE__, default)
end
def push(pid, item) do
GenServer.call(pid, {:push, item})
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, state) do
{value, list} = List.pop_at(state, 0)
{:reply, value, list}
end
@impl true
def handle_call({:push, item}, _from, state) do
{:reply, [item | state], [item | state]}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment