Skip to content

Instantly share code, notes, and snippets.

@mauricioabreu
Created July 25, 2018 03:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauricioabreu/8fdb64bef6a938dd1e34ac15e9268d4d to your computer and use it in GitHub Desktop.
Save mauricioabreu/8fdb64bef6a938dd1e34ac15e9268d4d to your computer and use it in GitHub Desktop.
Using Elixir pattern matching to check if a list has an event length of elements
// Write a function even_length? that uses pattern matching only to return false
// if the list you pass it has an odd number of elements, true otherwise.
def even_length?([_, _ | t]) do
even_length?(t)
end
def even_length?([_ | []]) do
false
end
def even_length?([]) do
true
end
@dsdshcym
Copy link

Even better:

  def even_length?([]) do
    true
  end

  def even_length?([_head | tail]) do
    !even_length?(tail)
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment