Is there any connection between the contravarience of Hom Functor and Scala's Function1?

280 views Asked by At

The Hom functor Hom(-,-) is contravariant in the first argument and covariant in the second.

Can this fact somehow offer another explanation why Scala's Function1[-T1, +R] has the same property?

I have seen this claim made for example here, but at the point where the connection between the two concepts was supposed to be explained, there was so much hand waving it blew me away.

2

There are 2 answers

0
Daniel Wagner On

Probably not if you're careful about the setup. Function1 is very analogous to (the object part of) the Hom functor -- except that its target is not quite the same category. The target of the Function1 mapping is (a subcategory of) the scala category that has Scala types as objects and functions as arrows; while the target of the Hom functor is (a subcategory of) SET. Their images are probably isomorphic, but it's not clear that combining the two functors and the isomorphism preserves the structure in the way you need for variance to be preserved across the whole chain.

8
n. m. could be an AI On

There are two categories of Scala types.

One is the usual types-and-functions category, where types are objects and arrows are functions.

The other one is the types-and-subtyping category, where types are objects and subtyping relationships are arrows. This category is a poset.

Covariance and contravariance in Scala is precisely covariance and contravariance of endofunctors in this latter category.

Now the second category happens to be a subcategory of the first one, due to projection arrows that map subtypes to supertypes. These arrows of the first category are exactly (all) the arrows of the second category. So every covariant endofunctor of the first category is naturally (that is, via a natural transformation) a covariant endofunctor of the second category.

Indeed, if a functor F maps A to A' and B to B' and every arrow f: A -> B to an arrow f': A' -> B', and if A is a subtype of B, then the projection arrow prj_A,B is mapped to a projection arrow prj_A',B', and if one exists, then A' is a subtype of B'. Same thing about contravariant functors.

Now it only remains to see that Function1 is in a sense the Hom functor. Indeed if we see a Scala type as a set of its values, then Function1[A,B] is a set of morphisms (Scala functions) from A to B. The arrow mapping is given by composition. And since it's covariant (contravariant) in the first category, it must be also covariant (contravariant) in the second category.

Edit:corrected subtype/supertupe confusion.

Disclaimer: I've never studied category theory. I may or may not know what I'm talking about.