我在尝试实现映射类(Bifunctor[Map[_, _]])时偶然发现了这个问题。
双函子在猫中是这样定义的:
/**
* 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))。我一直在想,是否有某种隐式类型转换,我不知道在这里发生。它怎麽工作?需要实现什么才能获得映射的双函子类型类?
发布于 2019-09-26 09:36:27
用于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)https://stackoverflow.com/questions/58112052
复制相似问题