-
-
Save freizl/1280336 to your computer and use it in GitHub Desktop.
Monad in JS
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
/* | |
jsclass | |
http://jsclass.jcoglan.com/ | |
npm install jsclass | |
*/ | |
require('jsclass'); | |
JS.require('JS.Deferrable'); | |
Promise = new JS.Class({ | |
include: JS.Deferrable, | |
initialize: function(value) { | |
if (value !== undefined) this.succeed(value); | |
} | |
}); | |
// foldl :: (a -> b -> a) -> a -> [b] -> a | |
function foldl (g, a, bs) { | |
var ret = a; | |
for (var i = 0, n = bs.length; i < n; i++) { | |
ret = g(ret, bs[i]); | |
} | |
return ret; | |
}; | |
// unit :: a -> Promise a | |
function unit(x) { | |
return new Promise(x); | |
}; | |
// wrap :: a -> Promise () -> void | |
function wrap(x, p) { | |
p.succeed(x); | |
}; | |
// bind :: Promise a -> (a -> Promise b) -> Promise b | |
function bind(input, f) { | |
var output = new Promise(); | |
input.callback(function(x) { | |
f(x).callback(function(y) { | |
output.succeed(y); | |
}); | |
}); | |
return output; | |
}; | |
exports.Promise = Promise; | |
exports.unit = unit; | |
exports.wrap = wrap; | |
exports.bind = bind; | |
exports.pipe = foldl.bind(null, bind); |
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
// invoke via : node test.js | |
var fs = require('fs'), | |
url = require('url'), | |
http = require('http'), | |
sys = require('util'), | |
p = require('./promise'); | |
// readFile :: String -> Promise String | |
var readFile = function(path) { | |
var promise = new p.Promise(); | |
fs.readFile(path, function(err, content) { | |
p.wrap(content, promise); | |
}); | |
return promise; | |
}; | |
// printUrl :: String -> Promise String | |
var printUrl = function(json) { | |
var uri = JSON.parse(json).url; | |
return p.unit(sys.puts(uri)); | |
}; | |
p.pipe(p.unit(__dirname + '/urls.json'), [readFile, printUrl ]); |
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
{"url":"http://github.com/api/v2/json/user/show/jcoglan"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment