Scala – Monads

  • date 28th April, 2021 |
  • by Prwatech |
  • 0 Comments

Demystifying the Monad in Scala

 

In Scala, Monads is a development which performs progressive computations. It is an object which covers the other object. Monad is not a class nor a trait, it is an idea. Maximum collections of Scala are Monads yet not every one of the Monads are collections, there are a few Monads which are compartments like Options in Scala. So, we can say that in Scala the information types that carries out map just as flatMap() like Options, Lists, and so on are called as Monads.

The Monad is a fundamental concept in functional programming that plays a pivotal role in managing and composing computations. In Scala, a Monad represents a computational context that supports operations like map and flatMap, facilitating sequence composition and error handling in a declarative manner.

At its core, a Monad encapsulates a value within a context, allowing sequential operations to be performed while handling side effects, error propagation, or asynchronous computations transparently. Monads enable developers to write pure and composable code by abstracting away common patterns of computation.

In Scala, common examples of Monads include Option for handling optional values, Future for representing asynchronous computations, and Try for managing computations that may result in success or failure.

Use case 1:

object prwatech
{
// Main method
def main(args:Array[String])
{

    // Creating list of numbers
    val list1 = List(1, 2, 3, 4)
    val list2 = List(5, 6, 7, 8)

    // Applying 'flatMap' and 'map'
    val z = list1 flatMap { q => list2 map {
            r => q + r
    }
    }

    // Displays output
    println(z)

}
}

Output

List(6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12)

Use case 2:

    object prwatech
    { 
    // Main method
    def main(args:Array[String])
    {   
    // Creating list of numbers
    val x = (1 to 5).toList
    val y = (1 to 6 by 2).toList

    // Applying 'flatMap'and 'map'
    val z = x flatMap { s => y map { 
                t => s * t 

    }
    }

    // Displays output
    println(z)
}
}

Output

List(1, 3, 5, 2, 6, 10, 3, 9, 15, 4, 12, 20, 5, 15, 25)

Use case 3:

    object prwatech
    {
    // Main method
    def main(args:Array[String])
    {
    // Creating list of numbers
    val a = (1 to 5 by 2).toList
    val b = (1 to 6 by 2).toList

    // Applying 'flatMap'and 'map'
    val x = a flatMap { y => b map { 
                t => y * t 

    }
    }

    // Displays output
    println(x)
}
}

Output

List(1, 3, 5, 3, 9, 15, 5, 15, 25)

Demystifying the Monad in Scala

Quick Support

image image