small medium large xlarge

Dave_gnome_head_isolated_pragsmall
15 Jul 2013, 03:42
Dave Thomas (390 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.

Generic-user-small
25 Aug 2013, 20:21
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
Generic-user-small
15 Jan 2015, 20:27
Pierre Sugar (57 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
U0x0gcxz_pragsmall
05 Apr 2015, 16:14
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
Generic-user-small
10 Jan 2017, 15:30
john invictus (5 posts)

My solution

defmodule Sequence.Stack do
  use GenServer

  def handle_call(:pop, _from, []), do: raise "Empty stack"

  #accessed using call
  def handle_call(:pop, _from,   [head|tail]) do
    {:reply, head, tail}
  end

  # when we dont need a rely
  #accessed using cast
  def handle_cast({:push, value}, state) do
    {:noreply, [value|state]}
  end

end
Generic-user-small
16 Feb 2017, 00:29
Oleg (15 posts)

Simple:

defmodule StackServer do
  use GenServer

  def handle_call(:pop, _from, stack) do
    {value, rest} = List.pop_at(stack, -1)
    {:reply, value, rest}
  end

  def handle_cast({:push, item}, stack) do
    {:noreply, List.insert_at(stack, -1, item)}
  end
end
Generic-user-small
25 Apr 2017, 09:45
Zoltán Vincze (4 posts)
defmodule Sequence.PopServer do

  use GenServer

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

  def handle_cast({:push, new_item}, current_list ) do
    { :noreply, [ new_item | current_list ] }
  end

end
You must be logged in to comment