zoukankan      html  css  js  c++  java
  • [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);   
  • 相关阅读:
    Python连接MySQL乱码(中文变问号)
    mysql学习04 pymysql 学习
    mysql学习03
    多态与多态性
    重用父类功能的两种方式
    菱形继承问题
    组合
    继承的应用和派生的概念引出
    类的继承
    类与类型
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10439093.html
Copyright © 2011-2022 走看看