Scala – Fold

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

Fold takes a twofold activity which consolidates every one of the components from the assortment and returns a solitary worth. The folds permits to characterize an underlying worth. Because of this property, fold can likewise oversee void assortments. On the off chance that the collection is unfilled, the value introduced turns into the last answer. Because of this we can likewise return an alternate worth from the arrangement of assortment utilizing beginning worth of some other datatype.

use case 1:

// Scala program sum of elements 
// using fold function 
// Creating object
object prwatech {
// Main method
    def main(arg:Array[String])
    {
        // initialize a sequence of elements
        val seq_elements: Seq[Double] = Seq(.5, 2.0, 1.1)
        println(s"Elements = $seq_elements") 
  
        // find the sum of the elements using fold function
        val sum: Double = seq_elements.fold(0.0)((a, b) => a + b)
        println(s"Sum of elements = $sum")
    }
}

output:

Elements = List(0.5, 2.0, 1.1)
Sum of elements = 3.6

use case 2:

object prwatech {
// Main method
    def main(arg:Array[String])
    {
        // initialize a sequence of elements
        val seq_elements: Seq[Double] = Seq(.5, 2.0, 1.1)
        println(s"Elements = $seq_elements") 
  
        // find the difference of the elements using fold function
        val sum: Double = seq_elements.fold(0.0)((a, b) => a - b)
        println(s"difference of elements = $sum")
    }
}

output:

Elements = List(0.5, 2.0, 1.1)
difference of elements = -3.6

use case 3:

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 fold function
        val concat: String = str_elements.fold("")(
                                (a, b) => a + "-" + b)
        println(s"After concatenation = $concat")
    }
}

output:

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

 

Quick Support

image image