O'Reilly logo

JavaScript: Functional Programming for JavaScript Developers by Dan Mantyla, Simon Timms, Ved Antani

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required