Another day, another Elixir fun exercise :-)

So today I’ve done another simple exercise, the http://exercism.io/exercises/elixir/sublist/readme, or how to determine if a list is a equal, sublist, superlist or unequal to another list. So, without further ado, here’s my take on it:

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) do
    cond do
      a === b ->
        :equal
      length(a) <= length(b) && is_sublist(a, b)->
        :sublist
      is_sublist(b, a) ->
        :superlist
      true ->
        :unequal
    end
  end

  defp is_sublist(a, b) do
    cond do
      length(a) > length(b) ->
        false
      a === Enum.take(b, length(a)) ->
        true
      true ->
        is_sublist(a, tl(b))
    end
  end
end
Advertisements
Tagged , ,

One thought on “Another day, another Elixir fun exercise :-)

  1. Felix says:

    Another version

    defp is_sublist?([], _), do: true
    defp is_sublist?(_, []), do: false
    defp is_sublist?([a|b], [a|c]), do: b === Enum.take(c, length(b)) || is_sublist?([a|b], c)
    defp is_sublist?([a|b], [_|c]), do: is_sublist?([a|b], c)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: