Saturday 11 June 2016

Functors, Monads and Monoids in Scala

1. Functors

A function X => Y is transformed to another function List[X]=>List[Y] by a higher order function called functor.

Functors

def functor[X, Y](f: X=>Y): List[X]=>List[Y] = {
      def fun: List[X] => List[Y] = (arg: List[X]) => arg match {
            case Nil => Nil
            case x :: xs => f(x) :: fun(xs)
      }
      fun
}

functor return a function that takes List[X], invokes f on each element, and returns List[Y].

Example: Map

The map method takes a function as a parameter and applies it to each element in a container in order to return a new container. The output container will be the same time as the input container.
This is because of a builder "canBuildFrom" builds an appropriate builder for the type of input collection.

2. Monads

A function X => List[Y] is transformed to another function List[X] => List[Y] by a high order function called Monad.

Monads

Monads are containers. They support higher order functions and can be combined
together. Roughly speaking, if a type F is a monad, you can combine multiple instances
of F , where some are chosen based on the values located inside the others.

def monad[X, Y](f: X=>List[Y]): List[X] => List[Y] = {
   def fun: List[X] => List[Y] = (arg: List[X]) => arg match {
          case Nil => Nil
          case x :: xs => f(x) ::: fun(xs)
   }
   fun
}

Example: FlatMap

The flatMap method takes a function (X => List[Y]) as a parameter, applies it to each element in a container, and flattens the overall result.

3. Monoids

Monoid needs to be associative and should have an identity value. Associative paves the way to parallelize operations.

Monoids

Example: FoldLeft.

Reference:


No comments:

Post a Comment