/var/log/messages

May 17, 2019 - 1 minute read - Comments - programming

プログラミング Elixir (30)

別場所にあった queue な課題をパクッて実装。

以下なカンジで動きました。

$ iex Stack.ex
Erlang/OTP 21 [erts-10.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]

Interactive Elixir (1.7.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Stack.start_link
{:ok, #PID<0.106.0>}
iex(2)> Stack.stack
[]
iex(3)> Stack.push(1)
:ok
iex(4)> Stack.stack  
[1]
iex(5)> Stack.push(2)
:ok
iex(6)> Stack.stack  
[2, 1]
iex(7)> Stack.push(3)
:ok
iex(8)> Stack.stack
[3, 2, 1]
iex(9)> Stack.pop
3
iex(10)> Stack.stack
[2, 1]
iex(11)> Stack.pop  
2
iex(12)> Stack.stack
[1]
iex(13)> Stack.pop  
1
iex(14)> Stack.stack
[]
iex(15)> Stack.pop  
nil

実装は以下です。

defmodule Stack do
  use GenServer

  def init(state), do: {:ok, state}

  def handle_call(:pop, _from, [value | state]) do
    {:reply, value, state}
  end

  def handle_call(:pop, _from, []), do: {:reply, nil, []}

  def handle_call(:stack, _from, state), do: {:reply, state, state}

  def handle_cast({:push, value}, state) do
    {:noreply, [value] ++ state}
  end

  def start_link(state \\ []) do
    GenServer.start_link(__MODULE__, state, name: __MODULE__)
  end

  def stack, do: GenServer.call(__MODULE__, :stack)
  def push(value), do: GenServer.cast(__MODULE__, {:push, value})
  def pop, do: GenServer.call(__MODULE__, :pop)
end

週末料理 囲碁

comments powered by Disqus