What do you do if you’ve done an exercise, it works, it’s not very inefficient and seems concise, then you go to the community solutions, sort by highest-rated user and see this?
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, b) when is_list(a) and is_list(b) do
case {contains?(a, b), contains?(b,a)} do
{true, true} -> :equal
{true, false} -> :superlist
{false, true} -> :sublist
{false, false} -> :unequal
end
end
# determines if list a contains list b. restore_a is needed to restore
# already "eaten" members of a, when b couldn't be matched completely
defp contains?(a, b, current_b \\ :initial, restore_a \\ nil)
defp contains?(a, b, :initial, nil), do: contains?(a, b, b, nil)
defp contains?(_, _, [], _), do: true
defp contains?([], _, _, _), do: false
defp contains?([x | a], b, [x | c], nil), do: contains?(a, b, c, a)
defp contains?([x | a], b, [x | c], restore_a), do: contains?(a, b, c, restore_a)
defp contains?([_ | a], b, _, nil), do: contains?(a, b, b, nil)
defp contains?(_, b, _, restore_a), do: contains?(restore_a, b, b, nil)
end
To clarify I enjoy creating solutions, and having to think, and play, but there is border.