Open In App

Recursion in Scala

Last Updated : 29 Mar, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Recursion is a method which breaks the problem into smaller sub problems and calls itself for each of the problems. That is, it simply means function calling itself. We can use recursion instead of loops. Recursion avoids mutable state associated with loops. Recursion is quite common in functional programming and provides a natural way to describe many Algorithms. Recursion is considered as to be important in functional programming. Scala supports Recursion very well.

Let us understand using the simple factorial example.
Example :




// Scala program of factorial using recursion
  
// Creating object
object GFG
{
    // Function define
    def fact(n:Int): Int=
    {
        if(n == 1) 1
        else n * fact(n - 1)
    }
      
    // Main method
    def main(args:Array[String])
    {
        println(fact(3))
    }
}


Output:

6

The above code demonstrated in a recursive approach to a factorial function, where the condition n == 1 results in a break from the recursion.

Let us understand more clearly by an example of gcd.
Example :




// Scala program of GCD using recursion
  
// Creating object
object GFG
{
    // Function defined
    def gcd(x:Int, y:Int): Int=
    {
        if (y == 0) x
        else gcd(y, x % y)
    }
      
    // Main method
    def main(args:Array[String])
    {
        println(gcd(12, 18))
    }
}


Output:

6

Problem with recursion is that deep recursion can blow up the stack if we are not careful.
Let’s understand this by using an example:
Example Code:




// Scala program of sum all numbers
// using recursion
   
// Creating object
object GFG
{
    // Function defined
    def sum(num: Int): Int=
    {
        if (num == 1)
            1
        else
            sum(num - 1) + num
    }
      
    // Main method
    def main(args:Array[String])
    {
        println(sum(55))
    }
}


Output:

1540

The method sum will do the summation of all the numbers. We reduce the num everytime and add it to the result. Here, whenever we call sum, it will leave input value num on the stack and using up memory every time. when we try passing a large input like sum(555555) than the output will be java.lang.StackOverflowError. This output means that the stack has been blown up.

The above example does not use tail recursion and is therefore not an optimal approach, especially if the starting value n is very large.

Tail Recursion

The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.
Let us understand it by a example:

Example :




// Scala program of factorial using tail recursion
import scala.annotation.tailrec
  
// Creating object
object GFG
{
    // Function defined
    def factorial(n: Int): Int =
    {
        // Using tail recursion
        @tailrec def factorialAcc(acc: Int, n: Int): Int =
        {
            if (n <= 1)
                acc
            else 
                factorialAcc(n * acc, n - 1)
        }
        factorialAcc(1, n)
    }
      
    // Main method
    def main(args:Array[String])
    {
        println(factorial(5))
    }
}


Output:

120

Here in the above code, we can use the @tailrec annotation to confirm that our algorithm is tail recursive.

If we use this annotation and our algorithm isn’t tail recursive, the compiler will complain. For instance, if we attempt to use this annotation on the above example of the factorial method, we will get the following compile-time error.

Example :




// Scala program of factorial with tail recursion
import scala.annotation.tailrec
  
// Creating object
object GFG
{
    // Function defined
    @tailrec def factorial(n: Int): Int =
    {
        if (n == 1)
            1
        else 
            n * factorial(n - 1)
    }
      
    // Main method
    def main(args:Array[String])
    {
        println(factorial(5))
    }
}


Output:

Could not optimize @tailrec annotated method factorial: it contains a recursive call not in tail position


Previous Article
Next Article

Similar Reads

Tail Recursion in Scala
Recursion is a method which breaks the problem into smaller subproblems and calls itself for each of the problems. That is, it simply means function calling itself. The tail recursive functions better than non tail recursive functions because tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recur
3 min read
Scala short &lt;(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short &lt;(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -&gt; &quot;geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &amp;() method with example
The &amp;() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &amp;() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert
2 min read
Scala Int &lt;(x: Char) method with example
The &lt;(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).&lt;(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Scala Int &lt;=(x: Double) method with example
The &lt;=(x: Double) method is utilized to return true if the specified int value is less than or equal to the double value, otherwise returns false. Method Definition: (Int_Value).&lt;=(Double_Value) Return Type: It returns true if the specified int value is less than or equal to the double value, otherwise returns false. Example #1: // Scala prog
1 min read
Scala Int &lt;=(x: Byte) method with example
The &lt;=(x: Byte) method is utilized to return true if the specified int value is less than or equal to the byte value, otherwise returns false. Method Definition: (Int_Value).&lt;=(Byte_Value) Return Type: It returns true if the specified int value is less than or equal to the byte value, otherwise returns false. Example #1: // Scala program of I
1 min read
Parameterless Method in Scala
Prerequisites - Scala | Functions A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle. Exa
2 min read
Scala short /(x: Short): Int
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The /(x: Short) method is utilized to return a result of the quotient operation on the specified Short value by the x. Method Definition: def /(x: Short): Int Return Type: It returns quotient with value and x. Example #1: // Scala program of Sho
1 min read
Scala List isEmpty Operation with example
The isEmpty operation is utilized to check if the stated list is empty or not. Syntax: m1.isEmpty Here, m1 is Map name. isEmpty is method which returns true if the stated list is empty else it returns false. Example #1: // Scala program of isEmpty() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating
1 min read
Scala Set dropRight() method with example
The dropRight() is utilized to return all elements except last 'n' elements. Method Definition: def dropRight(n: Int): Set[A] Return Type: It returns a set containing all elements except last 'n' elements. Example #1: // Scala program of dropRight() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating
1 min read
Scala Set equals() method with example
The equals() method is utilized to check whether the two sets have the same elements or not. Method Definition: def equals(that: Any): Boolean Return Type: It returns true if the elements of both the sets are same else it returns false. Example #1: // Scala program of equals() // method // Creating object object GfG { // Main method def main(args:A
1 min read
Scala Set drop() method with example
The drop() method is utilized to delete the first ‘n’ elements or to return all elements except first 'n' elements. Method Definition: def drop(n: Int): Set[A]] Return Type: It returns all elements except first 'n' elements. Example #1: // Scala program of drop() // method // Creating object object GfG { // Main method def main(args:Array[String])
1 min read
Scala Set dropWhile() method with example
The dropWhile() method is utilized to drop the longest prefix of elements from the set that satisfies the stated condition. Method Definition: def dropWhile(p: (A) =&gt; Boolean): Set[A] Return Type: It returns a set containing all the elements after dropping the longest prefix of elements from the set that satisfies the stated condition. Example #
1 min read
Article Tags :