Skip to content

Instantly share code, notes, and snippets.

@vasco3
Last active August 29, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasco3/bffcfca47d9f5baa0d76 to your computer and use it in GitHub Desktop.
Save vasco3/bffcfca47d9f5baa0d76 to your computer and use it in GitHub Desktop.
Monads

Monads

Macroids

function MONAD () {
  return function unit(value) {
    var monad = Object.create(null);
    monad.bind = function (func) {
      return func(value);
    };
    return monad;
  }
}

var unit = MONAD();
var monad = unit("HELLO WORLD");
monad.bind(alert);

Axioms

unit(value).bind(f) === f(value)

monad.bind(unit) === monad

monad.bind(f).bind(g) === monad.bind(function(value) {
  return f(value).bind(g);
});

Threads

Threads are evil. They cause race problems (due to threads) and deadlocks (due to mutual exclusion). Fix it with a single thread event-driven(eg. browsers) or message-driven(eg. NodeJS) system.

Single threaded servers

  • Elko (Java)
  • Twisted (Python)
  • NodeJS

Async is needed for single threaded servers to work. This is achieved with callbacks, but callbacks can turn into nested pyramids of doom. So another type of callbacks are promises, which handle better the async and can be written in a flat structure.

Law of turns

Never block. Never wait. Finish fast.

Promise Monad

A promise is an example of a monad.

From Douglas Crockford:

  • A value is not known when the monad is made
  • Each promise is linked to two resolver functions, keep and break, that determine the promise's success and value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment