Elixir for Loops
This is as thing we end up doing a lot in imperative code.
for (i = 0; i < 3; i++) {
console.log('whoop')
}
How do you do this sort of thing in Elixir with no for loop?
🤔
Enum
We’re doing something a number of times. That feels iterative, like something an Enum would handle.
Enum.each(["whoop", "whoop", "whoop"], fn(x) -> IO.puts(x) end)
This works, but it’s not flexible. Is there something better to iterate over?
Range
How about a Range? They’re easy to make.
iex(1)> i(1..3)
Term
1..3
Data type
Range
Description
This is a struct. Structs are maps with a __struct__ key.
Reference modules
Range, Map
Implemented protocols
IEx.Info, Inspect, Enumerable
Because it’s Enumerable, we can use
Enum.each
to loop over it.
Bingo
Enum.each(1..3, fn(_) -> IO.puts("whoop") end)
That works. Notice, though, Range is inclusive, so we do 1..3
. And since we
don’t actually care about the value of each item in the range, we use _
to
avoid a compiler warning about an unused variable.
RTFM
If you’re actually reading the docs, you would have run into this exact thing already.