For in Elixir
This Elixir code demonstrates various looping constructs that are similar to the original example. Here’s a breakdown of the differences and similarities:
Elixir doesn’t have a traditional
for
loop like many imperative languages. Instead, it uses comprehensions andEnum
functions for iteration.The first loop uses a comprehension with
Stream.repeatedly
to mimic a condition-based loop. This is not idiomatic Elixir, but it demonstrates how you could achieve a similar effect.The “classic” loop is replaced with
Enum.each
and a range, which is more idiomatic in Elixir.The range-based loop is also implemented using
Enum.each
.Elixir doesn’t have an exact equivalent to an infinite loop, but we can use
Stream.repeatedly
to create a similar effect. We usethrow
andcatch
to break out of the loop.The last example uses
Enum.each
with a conditional to demonstrate the concept of “continue”.
To run this program, save it as for_example.exs
and use:
Elixir’s functional nature leads to different idioms for iteration compared to imperative languages. The Enum
and Stream
modules provide powerful tools for working with collections and sequences.