How To Do A For Loop In Elixir (using only recursion)

If you wanted to implement a for loop as a re-usable concept, for the sake of understanding Elixir, recursion, pattern matching etc, then sure :slight_smile: I might do things very slightly differently;

defmodule ForLoop do

  def for_loop(count, action) when is_integer(count) and is_function(action) do
    loop(action, count, 0)
  end

  defp loop(_action, count, acc) when acc > count, do: :ok
  defp loop(action, count, acc) when acc <= count do
      action.(acc)
      loop(action, count, acc+1)
  end

end

However, in real life I’d just do as @thousandsofthem suggests, or use Enum.each:

Enum.each(0..10, &(IO.puts(&1)))
9 Likes