Hacker News new | past | comments | ask | show | jobs | submit login

If all you want is a counter to loop through something a given number of times, you could do something like this:

  defmodule Counter do
    def loop(num) do
      Enum.each(0..num, fn (i) -> IO.puts(i) end)
    end
  end
If you really want to write your own recursive function (Enum already does that for you, but it's always good to try different ways, so you can learn the language better), you could do something like this:

  defmodule Counter do
    def loop(num), do: _loop(0, num)
    defp _loop(idx, num) when idx == num, do: IO.puts idx
    defp _loop(idx, num) do
      IO.puts idx
      _loop(idx + 1, num)
    end
  end
The thing that is nice about Elixir is that it does tail-optimization on its recursive functions, as long as the recursive call is the very last thing in the function. This means you won't have 10 copies of the _loop function in memory waiting to unwind.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: