Home » Scala language

Monads in Scala

Scala | Monads: In this tutorial on Scala monads, we will learn about the monads with working code and examples.
Submitted by Shivang Yadav, on March 06, 2020

Scala | Monads

Monad is a tricky concept of the Scala programming language. It is a wrapper of the object type, an object that wraps another object. It is not a trait nor class. Also, most of the collections are monads but the reverse is not possible.

A monad is a data type that implements map and flatMap() like lists, options, etc.

Operations of monads

  • unit(): does not return any data type.
  • flatMap(): a map() like the method that returns a series of data types instead of a single component.

Let's take an example to understand the working of methods of monads.

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
		val setA = Set(4, 6, 8, 2) 
		val setB = Set(3, 5, 7, 1) 
		val multiple = setA flatMap { q => setB map { r=>q*r } } 
		
		print("Multiplication of SetA and SetB is : ")
		println(multiple)
	} 
} 

Output

Multiplication of SetA and SetB is : HashSet(14, 20, 6, 28, 2, 12, 18, 40, 8, 30, 4, 10, 56, 42, 24)

Explanation:

In the above program, to have used the flatMap() method to find the multiplication of elements of two sets. It has mapped (multiplied) each element of setA to all elements of setB. And the resultant is a set containing all possible maps.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.