15 Jul 2013, 03:42
Dave_gnome_head_isolated_pragsmall

Dave Thomas (340 posts)

  • Extend your stack server with a push interface which adds a single value to the top of the stack. This will be implemented as a cast.

    Experiment in iex with pushing and popping values.

25 Aug 2013, 20:21
Generic-user-small

Steve Downey (2 posts)

defmodule MyStack.Stack do
  use GenServer.Behaviour      

  def init(list)           
  when is_list(list) do
    { :ok, list }
  end

  def handle_call(:pop, _from, list) do
    [head | tail] = list
    { :reply, head, tail }
  end

  def handle_cast({:push, new_head}, list) do
    { :noreply, [new_head | list]}
  end
  
end
14 Dec 2014, 01:46
9863_pragsmall

Suraj Kurapati (15 posts)

Here’s my take on this problem:

defmodule StackServer do
  use GenServer

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

  def handle_cast({:push, value}, stack) do
    {:noreply, [value|stack]}
  end
end

{:ok, pid} = GenServer.start_link(StackServer, [5, "cat", 9])
:ok        = GenServer.cast(pid, {:push, 2})
10         = GenServer.call(pid, :pop) * GenServer.call(pid, :pop) # 2 * 5
"cat"      = GenServer.call(pid, :pop)
:ok        = GenServer.cast(pid, {:push, "meow"})
"meow"     = GenServer.call(pid, :pop)
9          = GenServer.call(pid, :pop)
15 Jan 2015, 20:27
Generic-user-small

Pierre Sugar (55 posts)

defmodule Stack.Stack do
  use GenServer

  def handle_call(:pop, _from, current_stack) when current_stack == [] do
    { :reply, :empty, [] }
  end
  def handle_call(:pop, _from, current_stack) do
    [ top | tail ] = current_stack
    { :reply, top, tail }
  end

  def handle_cast({ :push, value }, current_stack) do
    { :noreply, [ value | current_stack ] }
  end
end
05 Apr 2015, 16:14
U0x0gcxz_pragsmall

John Bohn (5 posts)

defmodule Stack.Server do
  use GenServer

  def init(stack)
  when is_list(stack) do
    { :ok, stack }
  end

  def handle_call(:pop, _from, []), do: raise "Empty stack"
  def handle_call(:pop, _from, [head | tail]) do
    { :reply, head, tail }
  end

  def handle_cast({:push, n}, stack) do
    { :noreply, [n | stack] }
  end
end
  You must be logged in to comment