函子

函子的作用:  在函数式编程中把副作用控制在可控范围内,函子也可以做异常处理,异步操作等。

什么是Functor(函子)

1. 容器:包含值和值的变形关系(这个变形关系就是函数)

2. 函子: 特殊的容器,通过一个普通的对象实现,这个对象具有map方法,map方法接收一个参数,

这个参数是一个纯函数,可以对值进行处理, 返回一个新的函子,新函子中保存了当前对值处理的结果,

新函子中又有一个map方法,你可以再给这个map传入一个新函数继续操作(也就是链式调用)

 1 // Functor函子
 2 class Container {
 3   //函子接收一个值
 4   constructor(value) {
 5     // 将这个值保存在内部变量_value中
 6     this._value = value;
 7   }
 8 
 9   //接收一个函数fn
10   map(fn) {
11     /**
12      * 返回的是一个新的函子,新函子接收的参数就是fn对内部变量_value处理后的新值,
13      * 然后这个新值被保存在新函子中 */
14     return new Container(fn(this._value));
15   }
16 }
17 
18 /**第一次map, 返回一个新函子,保存的值为6,其中有一个map方法,
19  * 第二次map,返回另一个新函子,保存的值为 6 * 6 = 36
20  */
21 let r = new Container(5).map((e) => e + 1).map((x) => x * x);
22 
23 console.log(r);
functor

结果

 

 

 

当然不想实例化,可以使用静态方法来初始化实例

 1 class Container {
 2     static of(value) {
 3         return new Container(value)
 4     }
 5 
 6     constructor(value) {
 7         this._value = value
 8     }
 9 
10     map(fn) {
11         return Container.of(fn(this._value))
12     }
13 }
14 // 测试
15 const newFunctor = Containers.of(3)
16   .map((x) => x + 2)
17   .map((x) => x * x);
18 
19 console.log(newFunctor);
View Code

结果

 

想象一下你传入null 或者undefined,  会发生什么

1 const newFunctor = Containers.of(undefined)
2   .map((x) => x + 2)
3   .map((x) => x * x);
4 
5 console.log(newFunctor);
View Code

 

 会出现异常,所以我们需要用到Maybe函子

 

posted @ 2021-02-10 11:08  芋圆小宝  阅读(272)  评论(0)    收藏  举报