初识函数式编程(三)

容器、Functor(函子)

函子,遵守特殊规定的容器
标志,具有map方法

//平平无奇的容器
var Container = function(x){
  this.__value = x;
}
Container.of = x=> new Container(x);
Container.of('abcd');

//map方法,变形关系,把当前容器中的值可以变形到另一个容器
Container.prototype.map = function(f){
  return Container.of(f(this.__value));
}
//函子
Container.of(3)        //Container(3)
                .map(x=>x+1)  //Container(4)
                .map(x=>'Result is '+x);//Container('Result is 4');

map

class Functor{
    constructor(val){
        this.val = val;
    }
    map(f){
        return new Functor(f(this.val));
    }
};

//Functor(4)
(new Functor(2)).map(function(two){
    return two+2;
});

of

纯函数,用来生成新的容器

Functor.of = function(val){
    return new Functor(val);
}

maybe函子

class Maybe extends Functor{
    map(f){
        return this.val?Maybe.of(f(this.val)):Maybe.of(null);
    }
}
//Maybe(null)
Maybe.of(null).map(function(s){
    return s.toUpperCase();
})

Either

左值是右值不存在时的默认值
右值是正常情况下使用的值

class Either extends Functor{
    constructor(left,right){
        this.left = left;
        this.right = right;
    }

    map(f){
        return this.right?Either.of(this.left,f(this.right)):Either.of(f(this.left),this.right);
    }
}

Either.of = function(left,right){
    return new Either(left,right);
}

var addOne = funcion(x){
    return x+1;
}
Either.of(5,6).map(addOne);     //Either(5,7)
Either.of(1,null).map(addOne);  //Either(2,null)
// Either.of({address:'xxx'},currentUser.address).map(updateField);

Ap函子

class Ap extends Functor{
    ap(F){
        return Ap.of(this.val(F.val));
    }
}
//Functor(4)
Ap.of(addTwo).ap(Functor.of(2));

IO

负责处理脏数据

你可能感兴趣的:(初识函数式编程(三))