Skip to content

Instantly share code, notes, and snippets.

@stockwellb
Created June 12, 2016 02:24
Show Gist options
  • Save stockwellb/d0bb76952a0b95161221bde8ef172540 to your computer and use it in GitHub Desktop.
Save stockwellb/d0bb76952a0b95161221bde8ef172540 to your computer and use it in GitHub Desktop.
Comparing lists for equal/sublist/superlist
defmodule Sublist do
def compare(a,b) when a === b, do: :equal
def compare(a,b) do
cond do
a === b -> :equal
sublist?(a,b) -> :sublist
sublist?(b,a) -> :superlist
true -> :unequal
end
end
defp sublist?([],_), do: false
defp sublist?(_,[]), do: false
defp sublist?(first, second=[_|tail]) do
if at_head?(first, second) do
true
else
sublist?(first, tail)
end
end
defp at_head?([],_), do: true
defp at_head?(_,[]), do: false
defp at_head?([a|restA], [a|restB]) do
at_head?(restA,restB)
end
defp at_head?(_,_), do: false
end
ExUnit.start
defmodule SublistTest do
use ExUnit.Case, async: true
test "A is a sublist of B(1)" do
assert :sublist == Sublist.compare([1,2,3], [1,2,3,4,5])
end
test "A is a sublist of B(2)" do
assert :sublist == Sublist.compare([3,4,5], [1,2,3,4,5])
end
test "A is a sublist of B(3)" do
assert :sublist == Sublist.compare([3,4], [1,2,3,4,5])
end
test "A = B" do
assert :equal == Sublist.compare([1,2,3], [1,2,3])
end
test "A is a superset of B" do
assert :superlist == Sublist.compare([1,2,3,4,5], [2,3,4])
end
test "A is not a superset of B" do
assert :unequal == Sublist.compare([1,2,4], [1,2,3,4,5])
end
test "A is not a subset of B" do
assert :unequal == Sublist.compare([1,2,3,4,5], [1,2,4])
end
test "A is not equal to B" do
assert :unequal == Sublist.compare([1,2,4], [1,2,3,4,5])
end
test "Empty list is in B" do
assert :unequal == Sublist.compare([],[1,2,3])
end
test "A is not in empty" do
assert :unequal == Sublist.compare([1,2,3], [])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment