Skip to content

Instantly share code, notes, and snippets.

@stken2050
Last active May 18, 2018
Embed
What would you like to do?
const isFunction = (m) => (typeof m === "function");
const isHigherOrder = (f) => isFunction(f("foo"));
const compose = (f, g) => (x => g(f(x)));
const isMonad = (m) => !(typeof m.val === "undefined");
const M = (m = []) => {
const f = m1 => {
const m1S = isMonad(m1) ? m1 : M(m1);
return !isFunction(m)
? M(m1S.val(m)) // a-f chain
: isHigherOrder(m1S.val)
? M(m1S.val(m)) //f-f curried function apply
: M(compose(m, m1S.val)); // f-f compose
};
f.val = m;
return isMonad(m)
? m
: f;
};
M.val = m => m;
const log = (m) => {
console.log(m);
return m;
};
M([1])(log);
const add1 = x => x + 1;
M(M)(log);
M(M(1))(log);
M([1, 2, 3])(([a, b, c]) => [a + 1, b + 1, c + 1])(log)
M(1)(add1)(add1)(log)
const add2 = M(add1)(add1);
M(100)(add1)(log);
M(100)(add1)(add1)(log);
M(100)(add2)(log);
const plus = (x) => (y => x + y);
M(plus(1)(5))(log);
const plus1 = plus(1);
M(plus1(5))(log);
M(5)(plus1)(log);
M(5)(M(1)(plus))(log);
const map = (f) => (array => array.map(f));
const map1 = M(add1)(map);
M([1, 2, 3])(log)(map1)(log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment