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:

 

scala> var name = Seq("Nikhil", "Mateo")
name: Seq[String] = List(Nikhil, Mateo)

scala> var exMap = name.map(_.toLowerCase)
exMap: Seq[String] = List(nikhil, mateo)

scala> var exMap = name.flatMap(_.toLowerCase)
exMap: Seq[Char] = List(n, i, k, h, i, l, m, a, t, e, o)

 

directly check the exact example of the monad:

val numList1 = List(1,2)
val numList2 = List(3,4)

numList1 flatMap { x => numList2 map {
   y => x + y
  }
}

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

without monad:

for {
     | first <- numList1
     | second <- numList2
     | } yield first + second
res11: List[Int] = List(4, 5, 5, 6)

 

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]):

  m map g = flatMap(x => unit(g(x)))

 

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.


Advertisements

About Nikhil Kumar

Senior Software Consultant at Knoldus Software LLP.
This entry was posted in Scala and tagged , , . Bookmark the permalink.

One Response to Simplifying Monads in Scala

  1. Pingback: Simplifying Monads in Scala | dotnetask

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s