# 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

*. And the resultant is a set containing all possible maps.*

**setB**TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

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