[Functional Programming] Unbox types with 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