Skip to content

Instantly share code, notes, and snippets.

@francisrstokes
Last active October 18, 2018 14:30
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 francisrstokes/e1f7d889abd087e1f1d6308abe808e61 to your computer and use it in GitHub Desktop.
Save francisrstokes/e1f7d889abd087e1f1d6308abe808e61 to your computer and use it in GitHub Desktop.
Monads
const daggy = require('daggy');
const {identity} = require('ramda');
const Either = daggy.taggedSum('Either', {
Left: ['__value'],
Right: ['__value'],
});
Either.of = Either.Right;
Either.prototype.map = function (fn) {
return this.cata({
Left: () => this,
Right: (x) => Either.Right(fn(x))
})
};
Either.prototype.join = function () {
return this.chain(identity);
};
Either.prototype.chain = function (fn) {
return this.cata({
Left: () => this,
Right: fn // Might be a type error 🙈
});
};
Either.prototype.ap = function (container) {
return this.map(container.__value);
};
module.exports = Either;
const daggy = require('daggy');
const Maybe = daggy.taggedSum('Maybe', { Just: ['__value'], Nothing: [] });
const { Just, Nothing } = Maybe;
Maybe.of = (x) => Just(x);
Maybe.prototype.map = function (fn) {
return this.cata({
Just: (x) => Maybe.of(fn(x)),
Nothing: Maybe.Nothing
});
};
Maybe.prototype.join = function () {
return this.cata({
Just: () => this.__value,
Nothing: () => Maybe.Nothing
});
};
Maybe.prototype.chain = function (fn) {
return this.map(fn).join();
};
Maybe.prototype.ap = function (container) {
return container.cata({
Just: (x) => this.map(x),
Nothing: () => Maybe.Nothing
});
};
module.exports = Maybe;
const daggy = require('daggy');
const {curry, compose} = require('ramda');
const fork = curry((err, succ, T) => {
return T.fork(err, succ)
});
const Task = daggy.tagged('Task', ['__value']);
Task.of = function (x) {
return Task((reject, resolve) => resolve(x));
};
Task.prototype.map = function (fn) {
return Task.of((reject, resolve) => {
this.fork(reject, compose(resolve, fn));
});
};
Task.prototype.chain = function (fn) {
return Task.of((reject, resolve) => {
this.fork(reject, compose(fork(reject, resolve), fn));
});
};
Task.prototype.fork = curry(function (errorFn, successFn) {
return this.__value(errorFn, successFn);
});
Task.prototype.ap = function (T) {
return T.chain(f => this.map(f));
};
module.exports = Task;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment