Monad – Introductory approach using Scala

Reading Time: 3 minutes

Overview

In this blog, I will try to keep everything beginner-friendly for monad in scala but still, you need some basic understanding of Scala that will help you get along. We will use terms like pure functions, side effects, etc very frequently in this blog so make sure you have a knack for it.

Monad?

Monad construction performs successive computations, it is an object that covers another object. Here we can say that the output of one computation can act as the input for other calculations. Monad is moreover a concept or way of doing things. Also as a result collections like List, Sequence, etc that support map and flat map in Scala are considered to be Monadic.

Example

val aSeq = Seq("Hello", "world")

Here “aList” is just a simple list where we will try to use the map() function on it which will look like this

val upperCaseMap = aSeq.map(_.toUpperCase())

If you try to print the value of upperCaseMap it’ll look like this: List(HELLO, WORLD)

Now, Let’s try to do the same thing with a flat map.

val upperCaseFlatMap = aSeq.flatMap(x => x.toUpperCase())

Now the output when we try to print the upperCaseFlatMap function looks like this :

List(H, E, L, L, O, W, O, R, L, D). So if you will notice flat map on applying on the seq is returning a list with removed inner grouping.

Use Case of Monad in scala

Suppose we need to make a class that prevents multi-threaded access to a value so let’s make a case class named “SafeValue”, we’ll make it generic say of type ‘T’ and covariant and let’s wrap an internal value say “internalValue” of type ‘T’.

object MonadForBeginners extends App {

  case class SafeValue[+T](private val internalValue: T){
    def get: T = synchronized {
      internalValue
    }
  }

  def safeValueTrigger[T](value: T): SafeValue[T] = SafeValue(value)

  val input = safeValueTrigger("Hello Safe Value")
  // Extract
  val inputString = input.get
  // Transform
  val upperString = inputString.toUpperCase()
  // Wrap
  val upperSafeInputString = SafeValue(upperString)
}

To make things easier we can make another function inside our case class so that it can do it all for me i.e extract, transform and wrap in a single go. So here is what it will look like.

object MonadForBeginners extends App {

  case class SafeValue[+T](private val internalValue: T){
    def get: T = synchronized {
      internalValue
    }

    def transformer[S](transform: T => SafeValue[S]): SafeValue[S] = synchronized{
      transform(internalValue)
    }
  }

  def safeValueTrigger[T](value: T): SafeValue[T] = SafeValue(value)

  val input = safeValueTrigger("Hello Safe Value")
  // Extract
  val inputString = input.get
  // Transform
  val upperString = inputString.toUpperCase()
  // Wrap
  val upperSafeInputString = SafeValue(upperString)

  // Compressed Form
  val upperBetterSafeInputString = input.transformer(s => SafeValue(s.toUpperCase()))

}

Now we can get rid of our extract transform and wrap. And this is where we have created a condition for a monad.

object MonadForBeginners extends App {

  case class SafeValue[+T](private val internalValue: T){
    def get: T = synchronized {
      internalValue
    }

    def transformer[S](transform: T => SafeValue[S]): SafeValue[S] = synchronized{
      transform(internalValue)
    }
  }

  def safeValueTrigger[T](value: T): SafeValue[T] = SafeValue(value)

  val input = safeValueTrigger("Hello Safe Value")

  val upperBetterSafeInputString = input.transformer(s => SafeValue(s.toUpperCase()))
  
}

So what exactly is a monad!

You can say monad has 2 fundamental behaviors, Firstly monad can wrap some value of let’s say type ‘T’ into another maybe more interesting value ” SafeValue in our case “. Secondly, the ability to transform this interesting value into some other interesting value.

Conclusion

This blog talks about the Monad concept and its structure. How to have a knack of it using scala. To know more about Knoldus check here. To read more blogs on various Scala-related technologies and other technologies check out knoldus blogs here.

knoldus

Leave a Reply