Home » Elixir » Elixir Loops
Welcome to a tutorial on Loops in Elixir.
As a result of immutability, loops in Elixir are written differently from imperative languages. Take a look at this example in an imperative language such as C, this code below will be written.
for(i = 0; i < 10; i++) {
printf("%d", array[i]);
}
In the above code, we are mutating both the array and the variable i. But, mutating is not possible in Elixir, rather functional languages rely on recursion. A function is called recursively until a condition is reached that stops the recursive action from continuing. Note that no data is mutated in this process.
Check the example of a simple loop using recursion that prints hello n times.
defmodule Loop do
def print_multiple_times(msg, n) when n <= 1 do
IO.puts msg
end
def print_multiple_times(msg, n) do
IO.puts msg
print_multiple_times(msg, n - 1)
end
end
Loop.print_multiple_times("Hello", 10)
The output is:
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
In the above example, we utilized the function's pattern matching techniques and recursion to successfully implement a loop. Recursive definitions are pretty difficult to understand but converting loops to recursion is easy and simple.
Enum module is provided by Elixir. This module is typically used for the most iterative looping calls as it is much easier to use those than trying to figure out recursive definitions for the same.
In the next tutorial, we will discuss more on this.
Note that your own recursive definitions should only be used when you don't find a solution using that module because those functions are tail call optimized and quite fast.