Skip to content

Instantly share code, notes, and snippets.

@MSakamaki
Last active April 23, 2016 03:25
Show Gist options
  • Save MSakamaki/b304dc0320f1b46095b8d106bf27e5aa to your computer and use it in GitHub Desktop.
Save MSakamaki/b304dc0320f1b46095b8d106bf27e5aa to your computer and use it in GitHub Desktop.
MONAD

モナド則

  1. bind(unit(x), f) ≡ f(x)
  2. bind(m, unit) ≡ m
  3. bind(bind(m, f), g) ≡ bind(m, x ⇒ bind(f(x), g))

JavaScript Primise Monado

  • return (unit) = Promise.resolve
  • bind = Promise.prototype.then
  1. bind(unit(x), f) ≡ f(x)
// bind(unit(x), f)
Promise.resolve(1).then( (v) => console.log(v) );
// f(x)
((v) => console.log(v) )(1);
  1. bind(m, unit) ≡ m
// bind(m, unit)
var m = Promise.resolve(1);
Promise.resolve(m).then((v) => console.log(v))
// m
var m = Promise.resolve(1);
m.then((v) => console.log(v) )
  1. bind(bind(m, f), g) ≡ bind(m, x ⇒ bind(f(x), g))
var m = Promise.resolve(2);
var f = (v) => Promise.resolve(v * 3);
var g = (v) => Promise.resolve(v + 2);

// bind(bind(m, f), g)
m.then(f).then(g)
.then((v) => console.log(v) );
// bind(m, x ⇒ bind(f(x), g))
m.then((x) => f(x).then(g))
.then((x) => console.log(x)) 

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment