初识函数式编程(三)

容器、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

负责处理脏数据

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 你可能听说过函数式编程(Functional programming),甚至已经使用了一段时间。但是,你能说清楚,...
    结构学AI阅读 5,523评论 0 3
  • 基本概念 函数式编程(Functional programming)与面向对象编程(Object-oriented...
    松哥888阅读 4,344评论 0 3
  • 现在大公司的编程方式有: 范畴论Category Theory 函数式编程是范畴论的数学分支是一门很复杂的数学,认...
    扶搏森阅读 4,547评论 0 0
  • 总之,在函数式编程中,函数就是一个管道(pipe)。这头进去一个值,那头就会出来一个新的值,没有其他作用。 一、函...
    定格r阅读 2,515评论 0 0
  • 在前端快速发展的今天,如果不能时刻保持学习就会很快被淘汰。分享一下最近学习的函数式编程的相关知识,希望对大家有所帮...
    gongyexj阅读 4,280评论 0 0