在阅读此博客上对 Functor 的描述时:
https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/
Functor 有一个通用定义和一个更具体的定义:
trait GenericFunctor[->>[_, _], ->>>[_, _], F[_]] {
def fmap[A, B](f: A ->> B): F[A] ->>> F[B]
}
trait Functor[F[_]] extends GenericFunctor[Function, Function, F] {
final def fmap[A, B](as: F[A])(f: A => B): F[B] =
fmap(f)(as)
}
显然,这意味着 Functor 可以与 Function 对象之外的其他更高种类的类型一起使用。有人可以举个例子或解释如何或为什么或在什么情况下会做?也就是说,在 Scala 中 GenericFunctor 的另一个实现会是什么——它使用与 Function 不同的类型构造函数?谢谢!
编辑:
只是为了澄清:
object Functor {
def fmap[A, B, F[_]](as: F[A])(f: A => B)(implicit functor: Functor[F]): F[B] =
functor.fmap(as)(f)
implicit object ListFunctor extends Functor[List] {
def fmap[A, B](f: A => B): List[A] => List[B] =
as => as map f
}
}
scala> fmap(List(1, 2, 3))(x => x + 1)
res0: List[Int] = List(2, 3, 4)
澄清一下,根据我的理解,ListFunctor 在 GenericFunctor 中实现 1-arg fmap,而 repl 脚本中的代码调用 Trait Functor 中的 fmap,而 Trait Functor 又调用 fmap 实现(例如在 ListFunctor 中)。
这不会改变整体问题,只是认为它会帮助人们试图提供答案。提供的任何见解将不胜感激。