Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Scala | Sequence Comprehensions

  • Last Updated : 12 Jul, 2021

Comprehensions have the structure for (enumerators) yield e, wherever enumerators refer to a semicolon-separated list of enumerators. Enumerator is either a generator that introduces new variables, or it’s a filter. A comprehension evaluates the body e for every binding generated by the enumerators and returns a sequence of those values. In this Scala offers a lightweight notation for conveying Sequence Comprehensions. In sequencing, it is possible to make multiple extractions without flat maps. This is possible by two methods by making cartesian product repeat or by Sequencing list of object. One more way to not use the flat map is to plan a special auto-generated syntax for Validation in Scala.
A sequence comprehension statement have generator part which generates a list of values from the specified range of inputs and a statement which operates on these generated elements which is then stored in the output list to be returned at the end of computation. Every datatype that supports the operations withFilter, map, and flatMap (with the proper types) can be used in sequence comprehensions.
Let’s understand some examples.
Example #1: 
 

Scala




// Scala program of sequence comprehensions
 
// Creating an object with extending APP
object CT extends App
{
    // Defining function with sequence comprehensions
    def even(from: Int, to: Int): List[Int] =
    for (a <- List.range(from, to) if a % 4 == 0) yield a
        Console.println(even(0, 20))
}

Output: 
 

List(0, 4, 8, 12, 16)

Here in example a new variable i of Integer is bounded to all value of list List(from, from + 1, …, to -1). If i % 4 == 0 it remove all the odd number from the list and gives the output for the number which is completely divisible by 4 between 0, 20.
Example #2: 
 

Scala




// Scala program of sequence comprehensions
 
// Creating object with extending App
object ComprehensionTest2 extends App
{
    // Defining function with sequence comprehensions
    def AddTill(n: Int, x: Int) =
        for (i <- 0 until n;
            j <- i until n if i + j == x) yield
        (i, j);
         
    // Calling function
    AddTill(12, 20) foreach
    {
        case (i, j) =>
        println(s"($i, $j)")
    }
}

Output: 
 

(9, 11)
(10, 10)

Here in the example shows that Sequence comprehensions does not get restricted to lists β€” every operation support flatMap. So the output calculates all pairs of numbers between 0 and n-1 whose sum is equal to a given value x.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :