Due to immutability, loops in Elixir (as in any functional
programming language) are written differently from imperative languages.
For example, in an imperative language like C, you would write:
Lets write a simple loop using recursion that prints hello n times.
Elixir provides us the Enum module to us which are used for most iterative looping calls as it is much easier to use those than trying to figure out recursive definitions for the same. We will discuss those in the next chapter. Your own recursive definitions should only be used when you dont find a solution using that module. Those functions are tail call optimized and quite fast.
for(i = 0; i < 10; i++) { printf("%d", array[i]); }In the example above, we are mutating both the array and the variable i. Mutating is not possible in Elixir. Instead, functional languages rely on recursion: a function is called recursively until a condition is reached that stops the recursive action from continuing. No data is mutated in this process.
Lets write 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)When running above program, it produces following result:
Hello Hello Hello Hello Hello Hello Hello Hello Hello HelloWe have utilized function's pattern matching techniques and recursion to successfully implement a loop. Recursive definitions are often quite short and difficult to wrap one's head around but converting loops to recursion is easy.
Elixir provides us the Enum module to us which are used for most iterative looping calls as it is much easier to use those than trying to figure out recursive definitions for the same. We will discuss those in the next chapter. Your own recursive definitions should only be used when you dont find a solution using that module. Those functions are tail call optimized and quite fast.
No comments:
Post a Comment