Functors and things using Scala[译]

Types of Functors

函数式编程中有很多functors类型,我们可以使用Scala编程语言对他们进行描述。

  • covariant functors —— 定义了mapfmap操作。
// covariant functor
trait Functor[F[_]] {
  def fmap[A, B](f: A => B): F[A] => F[B]
}
  • contravariant functors —— 定义了contramap操作。
// contravariant functor
trait Contravariant[F[_]] {
  def contramap[A, B](f: B => A): F[A] => F[B]
}
  • exponential functors —— 定义了xmap操作,也被称为invariant functors
// exponential functor
trait Exponential[F[_]] {
  def xmap[A, B](f: (A => B, B => A)): F[A] => F[B]
}
  • applicative functor[^1] —— 定义了apply或<*>操作。
// applicative functor (abbreviated)
trait Applicative[F[_]] {
  def apply[A, B](f: F[A => B]): F[A] => F[B]
}
  • monad[^2] —— 定义了bindflatMap或=<<操作。
// monad (abbreviated)
trait Monad[F[_]] {
  def flatMap[A, B](f: A => F[B]): F[A] => F[B]
}
  • comonad[^3] —— 定义了extendcoflatMap或<<=操作。
// comonad (abbreviated)
trait Comonad[F[_]] {
  def coflatMap[A, B](f: F[A] => B): F[A] => F[B]
}

Remembering the different types

有时我会被问到怎么记住这些,以及它们的使用场景。答案有很多,但是所有这些functor类型都有一个共同的特征:

They all take an argument that is some arrangement of three type variables and then return a function with the type F[A] => F[B].

我通过一个表格去记忆这些参数排列(argument arrangements)的类型,以便帮我决定哪个抽象(abstraction)是合适的。当然,我也使用其它的方法,但是这个小技巧(particular technique)非常优雅和短小。如下所示:

functorargument arrangement
covariantA => B
contravariantB => A
exponential(A => B, B => A)
applicativeF[A => B]
monadA => F[B]
comonadF[A] => B

从这张表中我们可以看出,我们没有更多的理由去强调其中一个而忽略其他。例如,monads获得了很多关注以及指责,但是这是不应该的,在更大的背景下,这是相当无聊的。它只不过是它的参数(A => F[B])的一个处理。

无论如何,这个表是一个很好的方法来检查不同类型的抽象以及它们可能如何应用。 也有从别人那里得到一些的方法,但这是另外一回事了。 这就是全部,希望它有所帮助!


  1. applicative functors也定义了一个identity操作,(def insert[A]: A => F[A]),然而,它省略了。
  2. monads也定义了一个identity操作,(def insert[A]: A => F[A]),然而,它省略了。
  3. comonads也定义了一个identity操作, (def extract[A]: F[A] => A),然而,它省略了。

转载于:https://my.oschina.net/igirl/blog/2222468

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值