6
votes

After studying the category theory based on MacLane, Awodey and Spivak books, I'm trying to understand free/operational monad in Haskell.

We can get a monad from just a data type by using Control.Monad.Free after transforming it to a functor with Data.Functor.Coyoneda, which is based on the mathematical background called Yoneda lemma.

But I'm not fully understanding the functor can be automatically generated by the deriving functor extension in GHC instead of relying on Yoneda lemma.

Is there any restriction to use the deriving functor in GHC compared to Data.Functor.Coyoneda?

1
maybe you'll find this blogpost helpfulRandom Dev

1 Answers

8
votes

Good question!

Coyoneda and DeriveFunctor do different things. Coyoneda creates a new, separate datatype which happens to be a Functor for any choice of argument. DeriveFunctor simply generates the boilerplate code for types which are functors by themselves. You can only derive a Functor instance for types for which you could write such an instance by hand.

Take newtype Pred a = Pred (a -> Bool) as a (somewhat contrived) example: there is no instance Functor Pred because Pred is contravariant in its a parameter, soDeriveFunctor won't be able to help you. On the other hand Coyoneda Pred is a Functor because Coyoneda f is a Functor, albeit not a very useful one, for any f.

As an aside, the Freer monad arises as an application of Free to Coyoneda.