diff --git a/solutions/elixir/sublist/1/lib/sublist.ex b/solutions/elixir/sublist/1/lib/sublist.ex new file mode 100644 index 0000000..e762c37 --- /dev/null +++ b/solutions/elixir/sublist/1/lib/sublist.ex @@ -0,0 +1,20 @@ +defmodule Sublist do + @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) do + cond do + sublist?(a, b) -> :sublist + sublist?(b, a) -> :superlist + true -> :unequal + end + end + + defp sublist?(a, a), do: true + defp sublist?(a, b) when length(a) > length(b), do: false + defp sublist?(a, [_ | b_tail] = b) do + if List.starts_with?(b, a), do: true, else: sublist?(a, b_tail) + end +end