3

Simplifying Monads in Scala

 3 years ago
source link: https://blog.knoldus.com/simplifying-monads-in-scala/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Simplifying Monads in Scala

Reading Time: 2 minutes

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:

xxxxxxxxxx
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:

xxxxxxxxxx
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:

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

xxxxxxxxxx
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.



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK