首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么猫双函子[F[_,_]].bimap函数中有两个参数群?

为什么猫双函子[F[_,_]].bimap函数中有两个参数群?
EN

Stack Overflow用户
提问于 2019-09-26 07:54:33
回答 1查看 219关注 0票数 0

我在尝试实现映射类(Bifunctor[Map[_, _]])时偶然发现了这个问题。

双函子在猫中是这样定义的:

代码语言:javascript
复制
/**
   * 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))。我一直在想,是否有某种隐式类型转换,我不知道在这里发生。它怎麽工作?需要实现什么才能获得映射的双函子类型类?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-26 09:36:27

用于Bifunctor的类型类Map的实例可以定义如下

代码语言:javascript
复制
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)被转换为

代码语言:javascript
复制
implicitly[Bifunctor[Tuple2]].bimap(x)(_.headOption, _.toLong + 1)

代码语言:javascript
复制
Bifunctor[Tuple2].bimap(x)(_.headOption, _.toLong + 1)

代码语言:javascript
复制
toBifunctorOps(x)(catsStdBitraverseForTuple2).bimap(_.headOption, _.toLong + 1)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58112052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档