Skip to content

Instantly share code, notes, and snippets.

Created June 29, 2018 06:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?

Forgetted Invariant Functors !

Invariant Functors

People tend to forget this quite often. An invariant functor or an exponential functor is:

Covariant Functor

That's the famous Functor ! Covariant functor implements xmap by discarding g: B => A

Contravariant Functor

As expected, it discards f: A => B and makes use of contramap to implement xmap

Example for Contravariant Functor


Example for covariant Functor

As expected, it is DecodeJson, where the type parameter in the type class comes at covariant position (method result)


If type parameters are at covariant position, that means the method return contains the type.

If type parameters are at contravariant position, that means the method parameters contain the type.

When is invariant functor?

We may have types at covariant (output) or contravariant (input) position. However, we may sometime deal with both covariance and contravariance in the same type class.

Let's bring in EncodeJson and DecodeJson into one type class.

EncodeJson and DecodeJson

Functor but invariant

So an individual map or contramap to upcast (or downcast) an A to B in the context of F[_] is not possible if F has types both in covariant and contravariant positions. It means, F has to have an invariant functor for it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment