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

here’s my simplified version from my previous post.

defmodule Loop.Basic do
  @spec loop(term, (term -> term), (term -> term), (term -> term)) :: list
  def loop(term, condition, transform \\ &(&1 + 1), fun \\ &(&1))
      when is_function(condition, 1) and is_function(transform, 1) and is_function(fun, 1) do
    do_loop(term, condition, transform, fun, [])
  end

  defp do_loop(current, condition, transform, fun, acc) do
    if condition.(current) do
      do_loop(transform.(current), condition, transform, fun, [fun.(current) | acc])
    else
      Enum.reverse(acc)
    end
  end  
end

Examples:

      iex> Loop.Basic.loop(1, &(&1 <= 5))
      [1, 2, 3, 4, 5]

      iex> Loop.Basic.loop(12345, &(String.length("#{&1}") <= 10), &(&1 * 7), &(:"#{&1}"))
      [:"12345", :"86415", :"604905", :"4234335", :"29640345", :"207482415", :"1452376905"]

it’s pretty functional in the mathematical sense of the word.

I called it basic, because functions only accept one argument (term)

Once I finished that, I was like…well, it gotta be concurrent as well,
so I ended up with a library.
https://github.com/eksperimental/loop/

please have a look at the sources:

and tell me what you think of it,
and if it can be improved in some way.

1 Like