exercism/elixir/sublist/lib/sublist.ex

23 lines
804 B
Elixir

defmodule Sublist do
@type result ::
:sublist
| :superlist
| :unequal
| :equal
@doc """
Returns whether the first list is a sublist or a superlist of the second list
and if not whether it is equal or unequal to the second list.
"""
def compare(a, a), do: :equal
def compare(a, b) when length(a) > length(b), do: (if subset?(b, a), do: :superlist, else: :unequal)
def compare(a, b) when length(a) < length(b), do: (if subset?(a, b), do: :sublist, else: :unequal)
def compare(_, _), do: :unequal
defp subset?(a, b, index \\ 0)
defp subset?([], _b, _index), do: true
defp subset?(a, b, index) when index + length(a) > length(b), do: false
defp subset?(a, b, index), do:
(if Enum.slice(b, index, length(a)) === a, do: true, else: subset?(a, b, index + 1))
end