Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Tail Recursion

4_tail_recursion.livemd

Tail Recursion

import IEx.Helpers

Section

defmodule ListFunctions do
  def count(list), do: count(list, 0)

  defp count([], acc) do
    acc
  end

  defp count([_first | rest], acc) do
    # 1. build accumulator
    new_acc = acc + 1
    # 2. call count
    count(rest, new_acc)
  end
end

# user calls: count([1,2,3])
{:module, ListFunctions, <<70, 79, 82, 49, 0, 0, 6, ...>>, {:count, 2}}
ListFunctions.count([1, 2, 3, 4, 5, 6])
6
ListFunctions.count([1, 2, 3, 4, 5, 6])
6