- Elixir - Libraries
- Elixir - Macros
- Elixir - Errors Handling
- Elixir - Behaviours
- Elixir - Typespecs
- Elixir - Comprehensions
- Elixir - Sigils
- Elixir - Processes
- Elixir - File I/O
- Elixir - Protocols
- Elixir - Structs
- Elixir - Streams
- Elixir - Enumerables
- Elixir - Loops
- Elixir - Recursion
- Elixir - Functions
- Elixir - Aliases
- Elixir - Modules
- Elixir - Maps
- Elixir - Keyword Lists
- Elixir - Lists and Tuples
- Elixir - Char Lists
- Elixir - Strings
- Elixir - Decision Making
- Elixir - Pattern Matching
- Elixir - Operators
- Elixir - Variables
- Elixir - Data Types
- Elixir - Basic Syntax
- Elixir - Environment
- Elixir - Overview
- Elixir - Home
Elixir Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Epxir - Loops
Due to immutabipty, loops in Epxir (as in any functional programming language) are written differently from imperative languages. For example, in an imperative language pke C, you will write −
for(i = 0; i < 10; i++) { printf("%d", array[i]); }
In the example given above, we are mutating both the array and the variable i. Mutating is not possible in Epxir. 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.
Let us now 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 the above program is run, it produces the following result −
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
We have utipzed function s pattern matching techniques and recursion to successfully implement a loop. Recursive definitions are difficult to understand but converting loops to recursion is easy.
Epxir provides us the Enum module. This module is 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. 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.
Advertisements