我保证,不再在网上又发布一篇Monad教程(By Erik Meijer)
自我娱乐,附赠各种Functional with OO,参见GitHub
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| Monad = function() { this.value = arguments[0]; }; Monad.prototype.unit = function (value) { this.value = value; return this; } Monad.prototype.bind = function (func) { var value = func(this.value); var monad = new Monad(value); return monad; } Monad.prototype.extract = function () { return this.value; }
var monad = new Monad; var monad = new Monad(10);
monad.unit(20); monad.unit(new Monad(30));
monad.bind(function (value) { return value }); var result = monad.bind(function (value) { return value.extract() * 2; })
console.log(result.extract());
var monad = new Monad; monad.unit(10);
console.log(monad.extract());
var firstMonad = monad.bind(function (value) { return value / 2; });
console.log(firstMonad.extract());
var secondMonad = monad.bind(function (value) { return value + 1; }).bind(function (value) { return value + 2; }).bind(function (value) { return value + 3; });
console.log(monad.extract()) console.log(secondMonad.extract());
|