Making the connection between JS for loops and Elixir for loops
When writing some Elixir code, I come across wanting to express something in a for loop. Of course there are constructs like each, map, reduce, and such in Elixir (and JavaScript), but I wanted to see to achieve the classic for loop in Elixir.
I only use JavaScript here since that was the language I used and studied extensively before diving deep into Elixir.
In JavaScript, the classic for loop looks like:
// JavaScript
for (var i = 0; i < a.size; i++) {
console.log(a[i])
}
In Elixir, using comprehensions and ranges, that would translate to:
// Elixir
for i <- 0..Enum.count(a) - 1 do
IO.puts(Enum.at(a, i))
end
If you wanted to unnest operations in the Elixir case, you could expand that to:
// Elixir (without nesting)
for i <- 0..Enum.count(a) - 1 do
a
|> Enum.at(i)
|> IO.puts()
end
I’m sure there are other ways to express this in Elixir as well, but I’ll get there eventually. Cheers!