var Container=function(value){ this.__value = value } //函数式编程通常约定,函子有一个of方法 Container.of=(x)=>(new Container(x))//Container.of('aaa') //通常约定,函子的标志就是容器具备map方法。该方法将容器里的每个值,映射到另外一个容器 Container.prototype.map=function(f){ return Container.of(f(this.__value)) } Container.of(2) .map(x=>x+1)//Container(3) .map(x=>console.log("x的值为",x))//Container("x的值为3")
class Functor{ constructor(val){ this._val=val } map(f){ return new Functor(f(this._val)) } } (new Functor(3)).map(x=>x+1)//Functor(4)
Functor.of=function(x){ return new Functor(x) } Functor.of(2).map(x=>x+1)//Functor(3)
Functor.of(null).map(x=>x.toUppercase())//TypeError class Maybe extends Functor{ map(f){ return this._val?Maybe.of(f(this._val)):Maybe.of(null) } } Maybe.of(null).map(x=>x.toUppercase())//Maybe(null) var Maybe = function(val){ this.val = val; } Maybe.of=function(x){ return new Maybe(x) } Maybe.prototype.map=function(f){ return isNothing()?Maybe.of(f(this.val)):Maybe.of(null) } Maybe.prototype.isNothing=function(){ return (!this.val == null) }
class Eitch extends Functor{ constructor(left,right){ this.left = left; this.right = right; } map(f){ reutrn this.right? Eitch.of(this.left,f(this.right)): Eitch.of(f(this.left),this.right) } } Eitch.of = function(left,right){ return new Eitch(left,right) } var addOne=function(x){ return x+1 } Eitch.of(5,6).map(addOne)//Eitch(5,7) Eitch.of(5,null).map(addOne)//Eitch(6,null) Eitch.of({address:"xxx"},currentUer.address).map(updateField)//代替try...catch
var Left = function(x){ this.__value = x } var Right = function(x){ this.__value = x } Left.of=x=>(new Left(x)); Right.of=x=>(new Right(x)); Left.prototype.map=function(f){ return this } Left.prototype.map=function(f){ return this } Right.prototype.map=function(f){ return Right.of(f(this.__value)) }
class AP extends Functor{ ap(f){ return AP.of(this._val(f.val)) } } AP.of(addTwo).ap(Functor.of(2))
function readlocalStorage(){ return window.localStorage(); }
import _ from 'lodash' var compose = _.flowRight;//函数由右至左执行 var IO = function(f){ this.__value = f; } IO.of=x=>new IO(x) IO.prototype.map=function(f){ return new IO(compose(f,this__value)) } //node var fs = require("fs"); var readFile=function(filename){ return new IO(function(){ return fs.readFileSync(filename,"utf-8") }) } //flatMap() 返回映射结果 readFile("../css3d/index.html").flatMap(tail).flatMap(print) //同等于 //chain返回一个lodash实例,该实例包含value启用显示方法链序列的封装 readFile("../css3d/index.html").chain(tail).chain(print)