Created
August 2, 2014 05:13
-
-
Save svanellewee/72c5eaa5b6a9857993d6 to your computer and use it in GitHub Desktop.
lazy monads... "fib monad"
This file contains 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
var list_monad = {} | |
// a -> [a] | |
list_monad.unit = function (value) { | |
return [value] | |
} | |
// (a -> [a]) -> ([a] -> [a]) | |
list_monad.bind = function(fn) { | |
return function(values) { | |
return values.map(fn) | |
} | |
} | |
var compose = function(f,g) { | |
return function(v) { return f(g(v)) } | |
} | |
var _unit = list_monad.unit | |
var _bind = list_monad.bind | |
var _compose = compose | |
// m >>= fn | |
var fn = function(elem) { | |
return elem * 2; | |
} | |
var pp = console.log | |
pp(_bind(fn)(_unit(1))) | |
pp(_bind(fn)((_bind(fn)(_unit(1))))) | |
pp(_bind(fn)([10,2])) | |
pp(_bind(fn)((_bind(fn)([10,2])))) | |
var unit = function(x,y) { | |
y = y || 1; | |
x = x || 0; | |
return [x,y] | |
} | |
var bind = function(afn) { | |
return function(value) { | |
var x = value[0] | |
var y = value[1]; | |
return [y, x+y] | |
} | |
} | |
pp(unit()[0]) | |
pp(bind()(unit())[0]) | |
pp(bind()(bind()(unit()))[0]) | |
function pipe(initval, functions) { | |
//ifunction = initval | |
val = initval; | |
for(var i = 0; i < functions.length ;i++) { | |
val = bind(functions[i])(val) | |
} | |
pp(">>",val[0]) | |
} | |
var fn = function(v){console.log("-->",v);} | |
pipe(unit(), []) | |
pipe(unit(), [fn ]) | |
pipe(unit(), [fn, fn ]) | |
pipe(unit(), [fn, fn, fn ]) | |
pipe(unit(), [fn, fn, fn, fn ]) | |
//console.log(results) | |
/* | |
~/source/nodejs$ node lazyfib.js | |
[ 2 ] | |
[ 4 ] | |
[ 20, 4 ] | |
[ 40, 8 ] | |
0 | |
1 | |
1 | |
>> 0 | |
>> 1 | |
>> 1 | |
>> 2 | |
>> 3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment