liveBook · Manning

Contravariant functor

As explained in Fabulous Adventures in Data Structures and Algorithms

A contravariant functor is a mapping between categories that preserves the existence of morphisms while reversing their directions.

A contravariant functor maps objects from one category to another while preserving morphisms but reversing their direction. For types, assignment compatibility supplies the morphisms: if Giraffe can be assigned to Animal, then an IC<Animal> can be assigned to an IC<Giraffe>. The interface receives the broader type because it compares or consumes values rather than producing them. section 7.3 section 7.4

Reversing a type relationship

With `interface IC<in T> { int CompareTo(T item1, T item2); }`, a value of type `IC<Animal>` can be assigned to a variable of type `IC<Giraffe>`. The original relationship points from Giraffe to Animal; applying `IC<T>` reverses it. Applying the mapping twice, as in `IC<IC<T>>`, restores the ordinary direction. section 7.3

abstract class Animal : Object {}
class Giraffe : Animal {}
class Tiger : Animal {}
interface IC<in T> 
{
    int CompareTo(T item1, T item2);
}

Inspect the C# declaration that marks the type parameter contravariant and restricts it to input positions. section 7.3

public void M(IC<Animal> ica)
{
    IC<Giraffe> icg = ica; #1
}

Inspect the assignment that makes the reversed compatibility relationship concrete. section 7.3

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Defines arrow reversal and demonstrates it with IC<T>, while stopping short of deeper category-theory development.
Examples
Uses Animal, Giraffe, IC<in T>, reversed assignment, and the double application IC<IC<T>>.
What it assumes
Uses C# generic interfaces and assignment compatibility while defining morphisms and categories at a high level.
What you can do after
Evaluate/understand why IC<Animal> can be assigned to IC<Giraffe> and why applying contravariance twice restores direction.
How it connects
Connects contravariant functors to categories, morphisms, endofunctors, assignment compatibility, and contravariant interfaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.