scheme|monad 例子

参考自:
Translation from Haskell to JavaScript of selected portions of the best introduction to monads I've ever read – The If Works
【scheme|monad 例子】haskell - What is a monad? - Stack Overflow
但是我依然不知道monad有什么用处^v^

/** * number => number * number => [number, String] //添加调试信息 * [number, String] => [number, String] //变成对称性,也就是可结合的 * 将对称性的函数使用compose进行链接 * 函数名不重要,重要的是抽象 * ===================abstraction=================== *///第一步,原始函数 var f = (x) => x + 2; var g = (x) => x * x; /** * 第二步,将原始函数(x) => x * 2 * 转变为 (x) => [x*2, "f被调用"] * 为了完成这一步,添加帮助函数unit * var unit = (x) => [f(x), "f 被调用"]; * 有点像恒等函数 x => x */ var unit = (x) => [x, ""]; var shiftF = (f) => x => [f(x), "f被调用"]; var shiftG = (g) => (x) => [g(x), "g被调用"]; /** * 第三步 * 将函数修改为对称的,也就是可结合的 * 即直接将入参变成出参的类型 */ var bind = (f) => (tuple) => { // console.log("tuple is " + tuple) var inputVal = tuple[0]; var inputMsg = tuple[1]; var val = f(inputVal); // console.log("val is " + val) if(inputMsg == ""){ return [val[0], val[1]]; } else { return [val[0], inputMsg + ", " + val[1]]; }}/** * 将函数结合起来 */ var compose = (f, g) => x => f(g(x)); /** * 需要的是满足对称性的函数 */ var reslut = compose(bind(shiftF(f)), bind(shiftG(g)))(unit(10)); console.log(reslut)// var reslut = compose(bind(shiftF(f)), bind(shiftG(g)))(10); // var reslut = compose(bind(shiftF), bind(shiftG))(10); // var show = console.log // var sg = shiftG(g)(10) // show(sg) // var bsf = bind(shiftF(f))([10, "test "]) // show(bsf)


    推荐阅读