Scala – Scan

  • date 30th May, 2021 |
  • by Prwatech |
  • 0 Comments

Scan operation accepts the binary operation as boundary and returns the incentive for every component in collections for that activity. It returns every cycle for that twofold administrator in the collections. In scan additionally we can characterize the underlying worth.

use case 1:

// Scala program sum of elements 
// using scan function 
// Creating object
object prwatech {
// Main method
    def main(arg:Array[String])
    {
        //initialize a sequence of numbers
        val numbers: Seq[Int] = Seq(3, 2, 1)
        println(s"Elements of numbers = $numbers")
  
        //find the sum of the elements using scan function
        val iterations: Seq[Int] = numbers.scan(0)(_ + _)
        println("Running total of all elements" + s"in the collection = $iterations")
    }
}

output:

Elements of numbers = List(3, 2, 1)
Running total of all elementsin the collection = List(0, 3, 5, 6)

use case 2:

// Scala program concatenate string 
// using scan function 
// Creating object
object prwatech {
// Main method
    def main(arg:Array[String])
    {
        // initialize a sequence of strings
        val str_elements : Seq[String] = Seq("hello", "Prwa", "Tech", "Bangalore")
        println(s"Elements = $str_elements")
  
        // Concatenate strings with scan function
        val concat : Seq[String]
                    = str_elements.scan("")((a, b) => a + "-" + b)
        println(s"After concatenation = $concat")
    }
}

output:

Elements = List(hello, Prwa, Tech, Bangalore)
After concatenation = List(, -hello, -hello-Prwa, -hello-Prwa-Tech, -hello-Prwa-Tech-Bangalore)

use case 3:

object prwatech {
// Main method
  def main(arg:Array[String])
    {
        // initialize a sequence of elements
        val seq_elements: Seq[Double] = Seq(0.5, 5.0, 1)
        println(s"Elements = $seq_elements") 
  
        // find the multiplication of the elements
        // using reduce function
        val sum: Double = seq_elements.reduce((a, b) => a * b)
        println(s"multiplicaion of elements = $sum")
    }   
}

output:

Elements = List(0.5, 5.0, 1.0)
multiplicaion of elements = 2.5

Quick Support

image image