If you are new to list recursion then you might find this a way to understand the concept. Given a arbitrary list [:a, :b, :elixir, :c, :d], recursing over the items in this list is conceptually like saying “process the first element of the list, then process the rest of the list”.
In Elixir that looks like:
def process_list([first | rest]) do
[process_element(first) | process_list(rest)]
end
Here the recursion is a very obvious implementation of the description. Process the first element, then process the rest of the list. Its recursive because the function is calling itself.
Will this work? It will to an extent. But what happens if the list is empty? Then there is no first and the function will raise an exception. So we need to cater for the empty list. And in this implementation there will always be an empty list because eventually there is no rest when the function recurses to the end. Therefore:
def process_list([]) do
[]
end
def process_list([first | rest]) do
[process_element(first) | process_list(rest)]
end
def process_element(:elixir), do: true
def process_element(_other), do: false
This is the simplest form of recursion (and I personally think its the most beautiful) but it won’t cater for all requirements. This form will always return a list the same length as the original list. In your case thats not what you want and therefore an accumulator may be required is order to build a new list. Which is what the great examples from @andrewb do.


















