在閱讀函子的描述在此博客:Scala - 如何在非函數類型上使用函子?
https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/
有函子的一個通用的定義,更具體的一個:
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)
}
顯然,這意味着函子可以與其它用於除函數對象外還有更高級的類型。有人可以舉一個例子或解釋如何或爲什麼或在什麼情況下會做?也就是說,GenericFunctor的另一個實現是在Scala中使用了一個與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成績單代碼調用特質的FMAP Functor,然後調用fmap實現(例如在ListFunctor中)。
這並沒有改變整體問題,只是認爲它會幫助人們試圖提供答案。任何見解提供將不勝感激。
我不認爲這兩個函子是一個仿函數。我看不出你將如何實施任一類別。 – Anonymous