dimitris papadimitriou
dimitris papadimitriou More than 12 years’ experience as full stack developer and Software Architect . Functional javascript with categories.

Introduction to Monads in Javascript (Video)

Introduction to Monads in Javascript (Video)

The idea : When we use map on a function f: a→ b we transform the value A inside the functor T(A) (using the container metaphor ) to a new type T(b) - Sometimes we may happen that type b is itself a T(a) so the function that we want to map is something like that f: a→T(a) In those situations we end up with something like T(T(a)) a Box in a Box situation (a Functor in a Functor) if T is a Monad it has a method Join that allows us to go back to the initial state T(a) or “unwrap” one layer.

For example, for the Identity Functor

1
2
3
4
const Id = (v) => ({
  value: v,
  map: (f) => Id(f(v))
});

if we use a function inside the map that returns an Id

1
Id(5).map(x=>Id(x+1))

Then we end up with this Id(Id(6)) how would you get out of this ? well if we drop the Id on the map map: (f) => Id (f(v)) would be fine. As you can see at the next figure, now after applying the function f at step 2 we just return the result immediately

So just for those times when we want to map to a functor we use another method instead of map called bind bind:(f) =>f(v),

1
Id(5).bind(x=>Id(x+1))  == Id(6)

The same reasoning goes for all functors, for example for the Array functor we can get the array-in-array situation easily:

1
[5,6].map(x=>[x+1]) === [[5], [6]]

The native array has a bind operation that is called flatMap [which actually is another usual name the Object-oriented Programming community likes to call the monadic bind]. So we should have used flatMap in the above example in order to get the correct array

1
[5, 6].flatMap(x => [x + 1]) === [5, 6] 

This might seem confusing, but the bind is a combination of two functors in one.

We are going to see some of the Monads. The most important are the Maybe,Either,and Promise :

  1. Maybe (aka Option) Monad in JavaScript
  2. Either Monad — A functional approach to Error handling in JS

Excerpt from the Book Functional Programming in Javascript in LeanPub https://leanpub.com/functional-programming-in-js-with-categories

comments powered by Disqus