Sha256: adb30c93b9e07e5a8874543d6344d8e48e807030cb9c5b358de8f08a1fce2f3d
Contents?: true
Size: 1.83 KB
Versions: 69
Compression:
Stored size: 1.83 KB
Contents
defmodule LinkedList do @opaque t :: tuple() @doc """ Construct a new LinkedList """ @spec new() :: t def new() do {} end @doc """ Push an item onto a LinkedList """ @spec push(t, any()) :: t def push(list, elem) do {elem, list} end @doc """ Calculate the length of a LinkedList """ @spec length(t) :: non_neg_integer() def length(list) do count_length(list, 0) end defp count_length({}, n), do: n defp count_length({_, t}, n), do: count_length(t, n + 1) @doc """ Determine if a LinkedList is empty """ @spec empty?(t) :: boolean() def empty?({}), do: true def empty?(_), do: false @doc """ Get the value of a head of the LinkedList """ @spec peek(t) :: {:ok, any()} | {:error, :empty_list} def peek({}), do: {:error, :empty_list} def peek({x, _}), do: {:ok, x} @doc """ Get tail of a LinkedList """ @spec tail(t) :: {:ok, t} | {:error, :empty_list} def tail({}), do: {:error, :empty_list} def tail({_, t}), do: {:ok, t} @doc """ Remove the head from a LinkedList """ @spec pop(t) :: {:ok, any(), t} | {:error, :empty_list} def pop({}), do: {:error, :empty_list} def pop({h, t}), do: {:ok, h, t} @doc """ Construct a LinkedList from a stdlib List """ @spec from_list(list()) :: t def from_list(list) do List.foldr(list, new(), &push(&2, &1)) end @doc """ Construct a stdlib List LinkedList from a LinkedList """ @spec to_list(t) :: list() def to_list(list) do list |> do_to_list([]) |> Enum.reverse() end defp do_to_list({}, acc), do: acc defp do_to_list({h, t}, acc), do: do_to_list(t, [h | acc]) @doc """ Reverse a LinkedList """ @spec reverse(t) :: t def reverse(list) do do_reverse(list, new()) end def do_reverse({}, acc), do: acc def do_reverse({h, t}, acc), do: do_reverse(t, push(acc, h)) end
Version data entries
69 entries across 69 versions & 1 rubygems