Created
November 25, 2013 06:34
-
-
Save andelf/7637199 to your computer and use it in GitHub Desktop.
Monad in javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function MONAD(modifier) { | |
| var prototype = Object.create(null); | |
| function unit(value) { | |
| var monad = Object.create(prototype); | |
| monad.bind = function (func, args) { | |
| return func.apply(undefined, | |
| [value].concat(Array.prototype.slice.apply(args || []))); | |
| }; | |
| if (typeof modifier == 'function') { | |
| monad = modifier(monad, value); | |
| } | |
| return monad; | |
| }; | |
| unit.method = function (name, func) { | |
| prototype[name] = func; | |
| return unit; | |
| }; | |
| unit.lift = function (name, func) { | |
| prototype[name] = function (args) { | |
| return unit(this.bind(func, args)); | |
| }; | |
| return unit; | |
| }; | |
| return unit; | |
| } | |
| var identity = MONAD() | |
| .lift('print', function(n) {console.log("Id", n);}) | |
| .lift('asNumber', function(n) { return Number(n); }); | |
| var m = identity("Hello World"); | |
| m.bind(console.log); | |
| m.print(); | |
| var m2 = identity("250.100"); | |
| m2.asNumber().print(); | |
| console.log(m2) | |
| var maybe = MONAD(funcion(monad, value) { | |
| if (value == null) { | |
| monad.bind = funcion () { return monad; }; | |
| } | |
| return monad; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment