Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Sequences in Maths
Next article icon

Scala | Sequence Comprehensions

Last Updated : 12 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
 



Next Article
Sequences in Maths

A

adityadubey10
Improve
Article Tags :
  • Scala
  • Scala

Similar Reads

  • Scala For Comprehensions
    Comprehensions have the structure for (enumerators) yield e, wherever enumerators refers 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
    3 min read
  • Comprehensions in Python
    Comprehensions in Python provide a concise and efficient way to create new sequences from existing ones. They enhance code readability and reduce the need for lengthy loops. Python supports four types of comprehensions: List ComprehensionsDictionary ComprehensionsSet ComprehensionsGenerator Comprehe
    4 min read
  • Sequences in LISP
    In Lisp, the ordered set of elements is represented by sequences. All the functionality we use in sequences is applied on vectors and lists which are two of the subtypes of sequences. Creating a Sequence:The generic function for creating a Sequence in Lisp is: ;The generic function for creating a Se
    7 min read
  • Scala String subSequence() method with example
    The subSequence() method is utilized to find the sub-sequence from the given String, And this sub-sequence starts and ends with the index we specify. Method Definition: CharSequence subSequence(int beginIndex, int endIndex) Return Type: It returns the resultant sub-sequence. Example: 1# // Scala pro
    1 min read
  • Sequences in Maths
    In mathematics, a sequence is an ordered list of numbers or objects that follows a specific rule or pattern. Each number in the sequence is called a term, and the position of a term in the sequence is determined by its index. Types of Sequences 1. Finite Sequence: A sequence that has a limited numbe
    3 min read
  • Scala | unapplySeq() method
    The unapplySeq() method is an Extractor method. It extracts an Object of particular type and then again reconstructs it into a Sequence of extracted values and the length of this Sequence is not specified at the time of compilation. So, in order to reconstruct an Object that contains a Sequence, you
    2 min read
  • Program to convert Java Set to Sequence in Scala
    A java Set can be converted to a Sequence in Scala by utilizing toSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert J
    2 min read
  • Lazy val and Infinite Sequences in Scala
    Vals and Lazy vals are present in Scala. lazy keyword changes the val to get lazily initialized. Lazy initialization means that whenever an object creation seems expensive, the lazy keyword can be stick before val. This gives it the advantage to get initialized in the first use i.e. the expression i
    3 min read
  • Scala | Methods to Call on a Map | Set-1
    Prerequisite- Scala Map. In Scala there are foremost Methods to call on a Map. A Scala Method is a section of a class which has a designation, a signature, optionally a few annotations, and whatsoever byte-code. A function which is interpreted as a member of some Object is termed as a Method and the
    11 min read
  • Methods to call on a Set in Scala
    A set is a collection that only contains unique items. In Scala, both mutable and immutable sets are available. The mutable set is those set in which the value of the object is change, but, in the immutable set, the value of the object is not changed itself. The immutable set is defined under Scala.
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences