Functional Programming — Functors

Image for post
Image for post
Photo by Julian Hanslmaier on Unsplash

The last blog in my functional programming series (will come back to this one day) is about functors.

A functor is simply something that can be mapped over.

Image for post
Image for post

“Something” is simply a set of values arranged in some shape. And ‘that can be mapped over’ means that for all the values in “something”, we can do something to it (call a function). And the resulting values will be back into a new container of the same structure and shape.

However, for a lot JavaScript objects, we can’t just map a function over it, because JavaScript objects usually don’t have a .map(f) method. We need to have a wrapper around it instead.

Similarly we can do it using the built-in Function.prototype:

There are two key laws for functors:

  • The identity law: => x) == functor

This means if the function inside the functor mapping applied simply return the input, then the resulting output should be the same to the original functor:

  • The composition law: => f(g(x))) ≡

You may notice that functor is just another way of composition.

Finally, as usual, just a few examples:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store