很多时候我们会遇到一些高阶类型F[_],但又无法实现它的map函数,也就是虽然形似但F不可能成为Functor。看看下面的例子:
trait Interact[A] case class Ask(prompt: String) extends Interact[String] case class Tell(msg: String) extends Interact[Unit]
Interact类型只容许两种实例:Ask继承了Interact[String], Tell继承Interact[Unit]。我们无法获取map[A,B]函数的B值,因而无法实现map函数了。但是,往往在一些场合里我们需要把F当做Functor来使用,如用Free Structure把F升格成Monad。也就是说我们需要把Interact当做Functor才能构建一个基于Interact的Free Monad。Scalaz里的Coyoneda与任何F[_]类型成同构(互等),而Coyoneda是个Functor,这样我们可以用Coyoneda来替代F。在上面的例子里我们只要得出F的Coyoneda,然后我们就可以用这个Coyoneda来替代F,因为它们是同构的。我们来看看Coyoneda的定义:scalaz/Coyoneda.scala
sealed abstract class Coyoneda[F[_], A] { coyo => /** The pivot between `fi` and `k`, usually existential. */ type I /** The underlying value. */ val fi: F[I] /** The transformer function, to be lifted into `F` by `run`. */ val k: I => A ... /** Like `lift(fa).map(_k)`. */ def apply[F[_], A, B](fa: F[A])(_k: A => B): Aux[F, B, A] = new Coyoneda[F, B]{ type I = A val k = _k val fi = fa } ... type Aux[F[_], A, B] = Coyoneda[F, A] {type I = B} /** `F[A]` converts to `Coyoneda[F,A]` for any `F` */ def lift[F[_],A](fa: F[A]): Coyoneda[F, A] = apply(fa)(identity[A])
type CoyonedaF[F[_]] = ({type A[α] = Coyoneda[F, α]}) import Isomorphism._ def iso[F[_]: Functor]: CoyonedaF[F]#A <~> F = new IsoFunctorTemplate[CoyonedaF[F]#A, F] { def from[A](fa: F[A]) = lift(fa) def to[A](fa: Coyoneda[F, A]) = fa.run }
object proof_coyo { trait _Coyoneda[F[_],A] { type I def k: I => A def fi: F[I] } def toCoyo[F[_],A](fa: F[A]) = new _Coyoneda[F, A] { type I = A val k = (a: A) => a val fi = fa } def fromCoyo[F[_]: Functor,A](coyo: _Coyoneda[F,A]): F[A] = Functor[F].map(coyo.fi)(coyo.k) }
trait Interact[A] case class Ask(prompt: String) extends Interact[String] case class Tell(msg: String) extends Interact[Unit] type coyoInteract[A] = Coyoneda[Interact,A]