Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Scala – Monads

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.

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)

The post Scala – Monads appeared first on Prwatech.



This post first appeared on Learn Big Data Hadoop In Bangalore, please read the originial post: here

Share the post

Scala – Monads

×

Subscribe to Learn Big Data Hadoop In Bangalore

Get updates delivered right to your inbox!

Thank you for your subscription

×