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.
This is a fun little exercise in Elixir. First we match a single item in the list (odd number) which is false. Then match exactly two items (even number) and return true. Then the 3rd function matches the first 2 elements (as throwaway) and recursively tails the list to match the first two patterns.
defmodule Lists do
def even_length?([_a]), do: false
def even_length?([_a, _b]), do: true
def even_length?([_a, _b | t]), do: even_length?(t)
end
Some testing below in IEx:
iex> Lists.even_length? [1]
false
iex> Lists.even_length? [1, 2]
true
iex> Lists.even_length? [1, 2, 3]
false
iex> Lists.even_length? [1, 2, 3, 4]
true