Maybe Functor

In notebook:
FrontEndMasters Hardcore Functional
Created at:
2017-04-03
Updated:
2017-07-15
Tags:
Functional Programming JavaScript Fundamentals

Functor

"An object or data structure you can map over"

functions: map

So basically if an object has a ​map​ function or method, then it's a functor (except for jQuery which didn't get this right).

Functor: anything with a ​map​ method

Them pesky nulls

  var getElement = document.querySelector
var getNameParts = compose(split(' '), getElement)

getNameParts('#full_name')
//=> ['Jonathan', 'Gregory', 'Brandis']

Partial application

(audience question)
Giving a curried function less arguments than it takes by definition. 
In the above example, ​split​ is partially applied.

Back to above example. 

If ​full_name​ is empty ​get('value')​ will also produce an error, the whole chain will collapse and blow up. 

Maybe

This is our first functor. This is an elegant solution to the above null value issue. 
  • Captures a null check
  • The value inside may not be there
  • Sometimes has two subclasses Just / Nothing (in Haskell and other languages, here we will only use one)
  • Sometimes called Option with subclasses Some/None
The above points relate to implementations across different languages. 

The idea is that you may or may not have a value in your functor

Maybe:

  var _Maybe.prototype.map = function(f) {
  return this.val ? Maybe(f(this.val)) : Maybe(null)
}

map(capitalize, Maybe('flamethrower'))
//=> Maybe('Flamethrower')
So if the value is truthy, we run the function on it, if not, we return null and don't even run the passed function.

so:
  map(capitalize, Maybe(null))
// Maybe(null)

We just abstracted out function application!

So wherever you add a maybe it will do a null check and if it's null will stop the chain and just return null.

Another example:

  var firstMatch = compose(first, match(/cat/g))

firstMatch('dogsup')
// Boom!

Blows up...

So we insert a Maybe inside it to protect it:

  var firstMatch = compose(map(first), Maybe, match(/cat/g))

firstMatch('dogsup')
// Maybe(null)
You can drop ​Maybe​ anywhere in your composition and "it" will go into it.

Above example: We cannot call ​first​ on ​Maybe​, we need to ​map(first)​ over it.