[Functional Programming] Unbox types with foldMap

本文介绍了如何使用'fold'操作简化JavaScript中'Concat'的使用,通过'immutable-ext'库的List和Map实现对Sum类型数据的聚合。首先,通过对比reduce和concat的使用,引入fold的概念。接着,展示了List和Map的fold应用,并引入了foldMap操作符以进一步简化代码。

Previously we have seen how to use Concat with reduce:

const res5 = [Sum(1), Sum(2), Sum(3)]
    .reduce((acc, x) => acc.concat(x), Sum.empty());
console.log("res5", res5);  // Sum(6)

 

To simply this, we can use 'fold':

const {Map, List} = require('immutable-ext');

const res6 = List.of(Sum(1), Sum(2), Sum(3))
    .fold(Sum.empty());
console.log("res6", res6); 

Javascript arrray doesn't have 'fold' so we use immutable-ext's List.

 

We can also use Map:

const res7 = Map({brian: Sum(3), sara: Sum(8)})
    .fold(Sum.empty());
console.log("res7", res7);  // Sum(11)

 

Normally, we don't have object contains Functor as values, then the easy way is mapping to Sum type:

const res8 = Map({brian: 3, sara: 8})
    .map(Sum)
    .fold(Sum.empty());
console.log("res8", res8); 

 

First Mapping then fold is common use case, then we can use  a shortcut opreator called 'foldMap':

const res9 = Map({brian: 3, sara: 8})
    .foldMap(Sum, Sum.empty());
console.log("res9", res9);   

 

转载于:https://www.cnblogs.com/Answer1215/p/10439093.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值