3 ms·
Any function defines a covariant function by postcomposition. Take for example the string-length function (len : string -> int). We can take any other function
by joppy 6y ago
Any function defines a covariant function by postcomposition. Take for example the string-length function (len : string -> int). We can take any other function which outputs a string, say (f : X -> string) where X is any fixed type, and produce a new function (g : X -> int) by g(x) = len(f(x)). So the len function defines a functor from the set of functions with signature (X -> string) to the set of functions with signature (X -> int). For concreteness, one can imagine this functor as replacing functions which output strings by functions which output the lengths of those strings instead.
However we can also treat (len : string -> int) as a contravariant functor by pre-composing instead of post-composing. Say we have a function (h : int -> Y), then we can form (k : string -> Y) by setting k(s) = k(len(s)). This could be useful if we only cared about whether a strings length were a multiple of 5, say.
Some of the above are lies: in order to call these functors in the mathematical sense (or the Haskell sense) you need to phrase things in just the right way. But I think it gets the idea across about how simple the difference between co- and contra- variance can be, with the example of replacing f(x) by g(f(x)) or by f(g(x)).
- magicalhippo 6y agoThank you for the example, this really helped me to grasp the concept. So given that I'm clueless when it comes to this topic, what kind of functions aren't functors? Those that take multiple parameters or something like that?