Self-Learn Yourself Scala in 21 Blogs – #6
Blog 6 – Recursion and Tail Recursion in Functional Programming.
Missed the previous blogs have a quick look with Self-Learn Yourself Scala in 21 Blogs (#1, #2, #3, #4, #5). In this blog let’s understand the recursion and tail recursion in functional programming.
Recursion is frequently used in Functional programming language. A classical example used to demonstrate recursion is computation of factorial.
def fact(n:Int):Int = if(n==0) 1 else n * fact(n-1)
Each level of recursive call uses a stack frame. Fortunately we don’t compute factorial for larger values of n as the factorial becomes huge for values more than 15. So it doesn’t occupy more stack.
Let us consider another example with lists.
def sum(a:List[Int]):Int = {if (a.isEmpty) 0 else a.head + sum(a.tail)}
Above example function is recursive, but it fails with stack overflow exception for larger lists due to larger usage of stack to make recursive calls.
The same recursion can be reconstructed using tail recursion which always uses single stack frame for its computation thereby avoiding stack overflow exceptions for larger recursions.
Ways to create Tail Recursion:-
- a) Define a helper function with accumulator(results accumulator) inside main function. This helper method should be called from main function with some initial value for accumulator. In this case initial value is zero.
def sum(a:List[Int]):Int = {
def loop(a:List[Int],acc:Int):Int={
if(a.isEmpty) acc
else loop(a.tail,acc + a.head)
}
loop(a,0)
}
b) now helper method calls itself for each recursion but it doesn’t maintain its reference on more than one stack frame. Hence this method works for lists of any size.
Infact many functions defined in Scala collections uses this technique to handle bigger collections efficiently, ofcourse with slight trade off in clarity of function.
Reference – Scala in Action by Nilanjan, and Communities.
Written By – Ramji Viswanathan, dataottam Guest.
Interesting? Please subscribe to our blogs at www.dataottam.com, to keep you trendy and for future reads on Big Data, Analytics, and IoT.
As, always please feel free to suggest or comment coffee@dataottam.com.