Elixir Recursion

Welcome to a tutorial on Elixir. Here you will learn about Recursion in Elixir.
 

About Exlixir Recursion

In general, Recursion is a method where the solution to a problem depends on the solutions to smaller instances of the same problem. Almost all computer programming languages support recursion by allowing a function to call itself within the program text.

The recursive functions have an ending condition ideally. However, this ending condition, which is also referred to as the base case stops reentering the function and adding function calls to the stack. At this point, the recursive function call stops. Check out the example below.

defmodule Math do
   def fact(res, num) do
   if num === 1 do
      res
   else
      new_res = res * num
      fact(new_res, num-1)
      end
   end
end

IO.puts(Math.fact(1,5))

The output is:

120

 

In the code above, with the function, Math.fact, we are calculating the factorial of a number. Take note that we called the function within itself.

For further clarification, we have provided the function with 1 and the number whose factorial we want to calculate. Then, the function checks if the number is 1 or not and returns res if it is 1 (thereby Ending the condition). But, if not, it then creates a variable new_res and assigns it the value of previous res * current num. after which It will return the value returned by our function call fact(new_res, num-1). Therefore, this repeats until we get num as 1. After that, we get a result.

Check out another example, of printing each element of the list one by one. We will utilize the hd and tl functions of lists and pattern matching in functions. This is shown below.

a = ["Hey", 100, 452, :true, "People"]
defmodule ListPrint do
   def print([]) do
   end
   def print([head | tail]) do 
      IO.puts(head)
      print(tail)
   end
end

ListPrint.print(a)

In the above code, the first print function is called when we have an empty list (ending condition). else, the second print function will be called which will divide the list into 2 and assign the first element of the list to the head and the remaining of the list to the tail. At this point, the head is printed and we call the print function again with the rest of the list, that is the tail.

The output is:

Hey
100
452
true
People