Monads
Let's say we have a function, X => List[Y]. This function is transformed to another function, List[X] => List[Y]. A higher order function that does this transformation is Monad.

Figure 9.2: Monad translation
Again, choosing the List container for ease of understanding, we go with the following commands:
object Monad extends App { def monad[X, Y](f: X => List[Y]): List[X] => List[Y] = { def fun : (List[X]) => List[Y] = (arg: List[X]) => arg match { // 1 case Nil => Nil case x :: xs => f(x) ::: fun(xs) // 2 } fun } def f1(n: Int) = (1 to n).toList // 3 val f = monad(f1) // 4 println(f(List(7,8,9))) // 5 }
The salient points of the preceding code are as follows:
- We define a function, - fun, that takes an argument,- arg, of the type- List[X].
- We iterate each element, - x, of the input list. We invoke- f(x)and get- List[Y]. We flatten each list by concatenating the resulting lists together with the- :::operator.
- We have a function... 
 
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                