Created
November 4, 2020 19:02
-
-
Save jon4syth/1583a92da3328e587d0779f9c5a3d3dc to your computer and use it in GitHub Desktop.
Sublist Exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Sublist2 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 a === b, do: :equal | |
# Passing the smaller list twice to is_sublist?/3 | |
def compare(a, b) when length(a) < length(b), do: if is_sublist?(a, b, a), do: :sublist, else: :unequal | |
def compare(a, b) when length(a) > length(b), do: if is_sublist?(b, a, b), do: :superlist, else: :unequal | |
def compare(_, _), do: :unequal | |
# When the smaller list is empty, all comparisons have been equal | |
defp is_sublist?([], _, _), do: true | |
# When the smaller list is NOT empty, and the larger list is empty, the last comparison was unequal | |
defp is_sublist?(_, [], _), do: false | |
# When both heads are equal, advance both lists. NOTE: use of the same variable name `h` for the pattern match | |
defp is_sublist?([h | t1], [h | t2], sublist_candidate) do | |
is_sublist?(t1, t2, sublist_candidate) | |
end | |
# When heads are not equal, advance larger list, restart comparison from the beginning of the sublist | |
defp is_sublist?(_l1, [_h|t2], sublist_candidate) do | |
is_sublist?(sublist_candidate, t2, sublist_candidate) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment