Current section
Files
Jump to
Current section
Files
lib/ergo/stack.ex
defmodule Ergo.Stack do
@moduledoc """
Context user-data represents a stack rather than a map or plain list, so we'll create
an interface that is more stack like than the list interface.
"""
@doc """
Create a new stack.
# Examples
iex> alias Ergo.Stack
iex> assert [] = Stack.new()
"""
def new() do
[]
end
@doc """
Push an element onto an empty stack
# Examples
iex> alias Ergo.Stack
iex> s = Stack.new()
iex> assert [1] = Stack.push(s, 1)
iex> assert [2, 1] = Stack.push(s, 1) |> Stack.push(2)
"""
def push(s, elem) when is_list(s) do
[elem | s]
end
@doc """
You cannot pop an element from an empty stack.
At this point it's not clear if this operation should raise an exception
or return an error. For now we'll return an error.
# Examples
iex> alias Ergo.Stack
iex> s = Stack.new()
iex> assert {:error, nil, []} = Stack.pop(s)
iex> s = s |> Stack.push(true) |> Stack.push(false)
iex> assert [false, true] = s
iex> assert {:ok, false, [true]} = Stack.pop(s)
"""
def pop([]), do: {:error, nil, []}
def pop([elem | s]) do
{:ok, elem, s}
end
@doc """
Get the top element of the stack without modifying the stack
# Examples
iex> alias Ergo.Stack
iex> s = Stack.new() |> Stack.push(1) |> Stack.push(2)
iex> assert 2 = Stack.peek(s)
"""
def peek([]), do: nil
def peek([elem | _]), do: elem
end