Functors

While morphisms are mappings between types, functors are mappings between categories. They can be thought of as functions that lift values out of a container, morph them, and then put them into a new container. The first input is a morphism for the type and the second input is the container.

Note

The type signature for functors looks like this:

// myFunctor :: (a -> b) -> f a -> f b

This says, "give me a function that takes a and returns b and a box that contains a(s), and I'll return a box that contains b(s).

Creating functors

It turns out we already have one functor: map(). It grabs the values within the container, an array, and applies a function to it.

[1, 4, 9].map(Math.sqrt); // Returns: [1, 2, 3]

However, we'll need to write it as a global ...

Get JavaScript: Functional Programming for JavaScript Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.