Onor.io
How To Do A For Loop In Elixir (using only recursion)
One question that came up for me when I first started with FP was how to do things that I was able to do in imperative without mutable variables. One that was tricky was trying to figure out how to do a for loop with no mutable variables. There are better ways to do this (which I am sure others will share) but this is what I’d consider the simplest way to do a for loop in Elixir via recursion:
# How to do a "for" loop in Elixir via recursion
defmodule ForLoop do
def for_loop(count, action) when is_integer(count) and is_function(action) do
acc = 0
loop(action, count, acc)
end
defp loop(action, count, acc) do
if acc <= count do
action.(acc)
loop(action, count, acc+1)
end
end
end
#Simply write out the numbers 0-10
ForLoop.for_loop(10,&(IO.puts(&1)))
Most Liked
thousandsofthem
Simplest way i know:
for x <- 0..10, do: IO.puts x
rvirding
I also think there is one benefit for basically everyone of implementing various types of loops explicitly using recursion, and that is to understand what is really going on. So while you might most of the time use libraries or provided constructs instead of actually explicitly doing yourself, really knowing what is going will make you a better programmer. It will allow you use libraries and provided constructs in a better way.
Robert
jwarlander
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
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)))
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









