Functors

Let's say we have a function, X => Y. This function is transformed to another function List[X] => List[Y]. A higher order function that does this transformation is Functor, as shown in the following diagram:

Functors

Figure 9.1: Functor translation

Here, we chose the List collection for ease of understanding. Instead of List, any collection will work (Refer to the next section for this):

object Functor extends App {

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

  val p = List("Hi", "there")

 def doubleEachChar(s: ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.