This made me wonder whether you can do a similar thing for Category itself. The answer is yes! For any Category k there is an embedding of k into the category of Haskell functions that preserves the category structure:

so there’s an alternative representation of Category instances that just needs (.) and id from the Prelude!

A technicality

Be careful though: not all forall r. k r a -> k r b arise from a k a b.

For the technically minded, fixing b and mapping a to k a b gives a contravariant functor (not a Functor!) from k to Hask. Call this functor k – b. The Yoneda embedding gives us a correspondence between k a b and natural transformations from k – a to k – b. Then the value of type (forall r. k r a -> k r b) that embed returns is always a natural transformation, but in much the same way that Dan Doel presented recently, not all values of that type need be natural transformations. The counterexamples to naturality here are thus exactly the complement of the image of embed. I haven’t thought about explicit examples. Please tell me if you have thought of one.

Lenses

There is an application of the Yoneda embedding to lenses themselves! An equivalent definition of Lens is

This gives another way of composing lenses using Prelude. However I cannot see how to make these lenses polymorphic and the composition is the opposite way round from what we might expect. The contravariant Yoneda embedding is better

but here I don’t see how to avoid using undefined to extract the getter and setter.

Functor

The contravariant embedding suggests some connection between Functor f => a -> f a and (a -> r, a -> r -> a), and more generally between Functor f => (a -> f a') and (a -> r, a -> r -> a'). I can’t see what this should be though.