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.

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

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

Create a website or blog at WordPress.com
%d bloggers like this: