当尝试为地图(Bifunctor[Map[_, _]]
)实现Bifunctior类型类时,我偶然发现了这个问题。
Bifunctor在猫中的定义如下:
/**
* The quintessential method of the Bifunctor trait, it applies a
* function to each "side" of the bifunctor.
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> val x: (List[String], Int) = (List("foo", "bar"), 3)
* scala> x.bimap(_.headOption, _.toLong + 1)
* res0: (Option[String], Long) = (Some(foo),4)
* }}}
*/
def bimap[A, B, C, D](fab: F[A, B])(f: A => C, g: B => D): F[C, D]
如注释所述,可以使用两个函数(在一个参数组中)作为其输入来调用此函数,如下所示:x.bimap(_.headOption, _.toLong + 1)
。这告诉我显然不是调用bimap
函数,因为该函数有两个参数组((fab: F[A, B])(f: A => C, g: B => D)
)。我一直想知道是否存在某种我不知道在这里发生的隐式类型转换。它是如何工作的?我需要实现什么才能获得地图的Bifunctor类型类?
答案 0 :(得分:5)
Bifunctor
的类型类Map
的实例可以定义如下
implicit val mapBifunctor: Bifunctor[Map] = new Bifunctor[Map] {
override def bimap[A, B, C, D](fab: Map[A, B])(f: A => C, g: B => D): Map[C, D] =
fab.map { case (k, v) => f(k) -> g(v) }
}
在x.bimap(_.headOption, _.toLong + 1)
中,隐式解析两次:
首先,找到实例Bifunctor[Tuple2]
(import cats.instances.tuple._
或import cats.instances.all._
或import cats.implicits._
),
其次,扩展方法已解决(import cats.syntax.bifunctor._
或import cats.syntax.all._
或import cats.implicits._
)
因此x.bimap(_.headOption, _.toLong + 1)
转换为
implicitly[Bifunctor[Tuple2]].bimap(x)(_.headOption, _.toLong + 1)
或
Bifunctor[Tuple2].bimap(x)(_.headOption, _.toLong + 1)
或
toBifunctorOps(x)(catsStdBitraverseForTuple2).bimap(_.headOption, _.toLong + 1)