Run a function N times

Ever wanted to run a function in Elixir N times?

If you come from the Ruby on Rails world (like I did), you might be looking for something like N.times { do_something }.

One Elixir solution is a little more verbose, but I really like it because it uses the Stream module!

You can create a function you want to run repeatedly with Stream.repeatedly. Then, when you want to run that N times, you Enum.take(N)!

n = 5

Stream.repeatedly(fn ->
  IO.puts "Hello world!"
end)
|> Enum.take(n)

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.