Sunday, February 16, 2014

JavaScript Monads



Douglas Crockford: JavaScript the Good Parts  @ pluralsight

DouglasCrockford/monad @ GitHub

a monad is a structure that represents computations defined as sequences of steps.
  • a monad consists of a type constructor M and two operations, bind and return (where return is often also called unit). 
  • The return operation takes a value from a plain type and puts it into a monadic container using the constructor, creating a monadic value. 
  • The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline, possibly with additional checks and transformations.
"Identity monad" (wrapper around a value)

    function MONAD() {
        return function unit(value) {
            var monad = Object.create(null);
            monad.bind = function (func) {
                return func(value);
            };
            return monad;
        };
    }
    var identity = MONAD();
    var monad = identity("Hello world.");
    monad.bind(alert);

result equivalent to: alert("Hello world.");


Because of its functional nature, JavaScript is a good platform for monads.
In fact, many libraries, including pervasive jQuery are extensively using monads.




Extensive usage of JavaScript can't be avoided anymore in web development.
Even on server side node.js sometimes has better efficiency than other languages.

JavaScript has elements of Lisp in disguise...
This is "a revenge of Lisp:" to get powerful effects like Lisp,
JavaScript code becomes as cryptic as Lisp's...

Many JavaScript libraries and frameworks
that could be used without real understanding,
But this may be like an early "singularity".
(i.e. put a dog on a airplane, it will arrive to a destination
without any understanding what happened; no offence to dogs)