Search code examples
scalascala-cats

How to explicitly summon and use Functor for function


import scala.language.higherKinds
import cats.Functor
import cats.instances.list._
import cats.instances.function._

val list1 = List(1, 2)

val list2 = Functor[List].map(list1)(i => i + 1)

But things don't work so smoothly for functions,

val f1 = (i: Int) => i.toString
val f2 = (s: String) => s

And we have to resort to type trickery,

scala> type TTT[A] = Int => A
// defined type alias TTT

scala> val ff = Functor[TTT].map(f1)(f2)
// ff: TTT[String] = scala.Function1$$Lambda$607/69160933@3a689738

Well... Is there a more direct way to solve this, as this tends to get very tedious for complex functions.


Solution

  • You can write

    val ff = Functor[Int => ?].map(f1)(f2)
    

    if you add addCompilerPlugin("org.spire-math" %% "kind-projector" % "0.9.7") to build.sbt.

    Or you can import functor syntax import cats.syntax.functor._ and then write with type ascription

    val ff = (f1: TTT[String]).map(f2)
    

    or with explicit type annotation

    val f1: TTT[String] = (i: Int) => i.toString
    val ff = f1.map(f2)