for loop in elixir

For Loop in Elixir

In Elixir, you can use the for loop construct to iterate over a collection and perform a set of operations for each element. The for loop in Elixir is similar to a list comprehension and allows you to generate a new list based on the elements of an existing list.

Here's the syntax for a for loop in Elixir:

for element <- collection do
  # operations to perform for each element
end
  • element is a variable that represents each element of the collection.
  • collection is the list or enumerable that you want to iterate over.

You can also include filters and transformations within the for loop to further manipulate the elements. Here's an example that demonstrates the usage of a for loop in Elixir:

numbers = [1, 2, 3, 4, 5]

for number <- numbers, rem(number, 2) == 0 do
  IO.puts("Even number: #{number}")
end

In this example, the for loop iterates over the numbers list and prints only the even numbers.

Please note that Elixir encourages the use of higher-order functions like Enum.map, Enum.filter, and Enum.reduce instead of explicit for loops in most cases. These higher-order functions provide a more functional programming style and are often more idiomatic in Elixir.