Last active
March 20, 2019 00:00
-
-
Save sofakingworld/58c8e7903e7de05cf3cfc5d2a1cbce44 to your computer and use it in GitHub Desktop.
Elixir Genserver#1
This file contains hidden or 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 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