Skip to content

Instantly share code, notes, and snippets.

@ken-okabe
Last active May 18, 2018 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ken-okabe/d59c23cb0d68630933d31e2e7faeb27f to your computer and use it in GitHub Desktop.
Save ken-okabe/d59c23cb0d68630933d31e2e7faeb27f to your computer and use it in GitHub Desktop.
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