Best way to simulate a for loop in Elixir?
There are many ways of doing it. You can just write your own recursive function or follow other examples mentioned here.
You can also define your "block" of code as a separate function (anonymous or named) and use it in Enum.each
or Enum.map
depending on what exactly needs to be returned.
Or actually use for like this:
for x <- 0..10 do
yor_block_of_code
end
You have a good enough solution right in your question. Enum.each
is one bona fide way to apply a function X number of times.
Maybe if we format it differently, you might see what you can do:
Enum.each(0..99, fn(_x) ->
IO.puts "hello, world!"
end)
The function is just like any other function, except that it is defined inline.
So, just add more lines of code ...
Enum.each(0..99, fn(x) ->
IO.puts "hello, world!"
IO.puts x
end)
If you want to reference a defined function, you can pass a function signature:
defmodule Test do
def bar(x) do
IO.puts "hello, world!"
IO.puts x
end
def foo do
Enum.each(0..99, &bar/1)
end
end