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)