Simplifying Monads in Scala

Monads are not at all a complex topic, but yes it comes under the advanced section of Scala language. So basically Monads is a structure that represents sequential computations.

Monads is a structure that represents sequential computations, Monad is not a class or a trait; monad is a concept.

A monad is an object that wraps another object in Scala, In Monad the output of a calculation at any step is the input to the other calculation which runs as a parent to the current step.

One positive point: you already know about flatMap in Scala and you know how to access the future value using combinators and that consists flatMap, this way you already know what is the use case of flatMap., it flattens the resulting list of strings into a sequence of characters, see below example:

 

 

directly check the exact example of the monad:

output: res10: List[Int] = List(4, 5, 5, 6)

without monad:

 

FlatMap is way more powerful than map. It gives us the ability to chain operations together, as you’ve seen in the examples section. Map functionality is just a subset of flatMap functionality.

If you want to have map() available in your monad, you can express it using monad’s existing methods flatMap() and unit() like this

(note that g is some function Int → Something, not Int → List[Something]):

 

Note: This is a quick note post about Monads & I will be adding the content related to this soon.

 

This is though not a complete info but now we got the practical idea behind monads if you have suggestions please share, that would be a great learning.


Written by 

Principal Architect at Knoldus Inc

2 thoughts on “Simplifying Monads in Scala

Leave a Reply

%d bloggers like this: