O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required