码迷,mamicode.com
首页 > 其他好文 > 详细

[Functional Programming] Unbox types with foldMap

时间:2019-02-26 19:29:38      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:nal   case   app   call   span   OLE   bsp   imp   orm   

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);   

 

[Functional Programming] Unbox types with foldMap

标签:nal   case   app   call   span   OLE   bsp   imp   orm   

原文地址:https://www.cnblogs.com/Answer1215/p/10439093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!