Scala | Sequence Comprehensions
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.
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.
(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.