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.
- Scala For Comprehensions
- Comprehensions in Python
- Program to convert Java Set to Sequence in Scala
- Nested List Comprehensions in Python
- Scala Tutorial – Learn Scala with Step By Step Guide
- Wrap Around Concept and TCP Sequence Number
- Set in Scala | Set-1
- Scala | Either
- Set in Scala | Set-2
- Scala Map
- Comments In Scala
- Scala ListBuffer
- Inner class in Scala
- Scala Constructors
- Queue in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : SohomPramanick