r/javascript • • Jul 19 '16

JavaScript Functors Explained

http://freecontent.manning.com/javascript-functors-explained/
5 Upvotes

14 comments sorted by

View all comments

Show parent comments

3

u/jellatin Jul 19 '16 edited Jul 19 '16

Edit: totally forgot /u/jnd-au helped me understand this a few months ago: https://www.reddit.com/r/functionalprogramming/comments/4e9evj/trying_to_wrap_my_head_around_lift/

First things first, imo Professor Frisby's Mostly Adequate Guide to Functional Programming is the de facto standard for learning about FP in JavaScript. You don't get to Functors/Lifting until Chapter 8 which assumes understanding of the previous chapters but even without reading the prior chapters it's still more clear than the excerpt posted here.

The other problem here is that the author describes "lifting" incorrectly. Lifting is the idea of "teaching" something, say a function, how to work with values inside of a container.

Simple example:

function add2(n) {
  return n + 2;
}

Our add2 function understands how to work on single values like Numbers. If you give it a number, you will get a new number back that's 2 higher than the one you gave it. Great.

But what if I want to do this for a number inside of a container?

var myArr = [5];

add2(myArr) // error (in actuality you're going to get "52" as JS will cast to string and + will concat, but I think it's safe to say this is not our desired behavior)

The problem here is that add2 doesn't understand container/functor space. It needs to be lifted into this space, which is exactly what map can do for us.

map(myArr, add2);  // [7]

(Side Note: If you want to get a map function rather than method try this: var map = Function.prototype.call.bind(Array.prototype.map);)

Ignore the fact that people usually use map to work on multiple values inside of an array, it's irrelevant for this example. What you see here is a function being lifted into container/functor context.

Now that you see this working, understand that it can work on all sorts of different containers that can be built to do other cool things for you.

This guide may be slightly more advanced than where you're at but the pictures might help you understand what's happening with the containers: http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html