Scala – Fold Right

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

Scala Collections FoldRight Method


The foldRight work is relevant to both Scala's Mutable and Immutable assortment information structures.

The foldRight technique takes an affiliated parallel administrator work as boundary and will utilize it to implode components from the assortment. The request for navigating the components in the assortment is from option to left and thus the name foldRight. The foldRight technique permits you to likewise determine an underlying worth.

The foldRight is a method in Scala collections is a higher-order function that facilitates iterative processing and aggregation of elements from right to left within a collection. This method is define on sequences (e.g., List, Vector) and operates by recursively applying a binary operator to combine elements of the collection starting from the rightmost element.

The signature of foldRight is foldRight[B](z: B)(op: (A, B) => B): B, where:

  • z is an initial value of type B used as the starting accumulator.
  • op is a binary operator that takes an element of the collection of type A and an accumulator of type B, and produces a new accumulator of type B.

The foldRight method processes elements in reverse order compared to foldLeft, making it suitable for operations that require a right-associative combining function (e.g., constructing new collections, performing recursive computations).Scala Collections FoldRight Method

use case 1:

The code below shows how to sum all the donut prices from the sequence by using the foldRight method.

scala> val prices: Seq[Double] = Seq(1.5, 2.0, 2.5)
scala> val sum = prices.foldRight(0.0)(_ + _)

2use case 2:

Create a String of all  using foldRight function
scala> val eduprwa: Seq[String] = Seq("Data", "Science", "Prwatech")
scala> println(s"All eduprwa = ${eduprwa.foldRight("")((a, b) => a + " eduprwa " + b)}")

use case 3:

scala> val prices: Seq[Int] = Seq(1, 2, 2)
scala> val sum = prices.foldRight(0.0)(_ - _)

Quick Support

image image