[Functional Programming] Unbox types with foldMap
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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);
以上是关于[Functional Programming] Unbox types with foldMap的主要内容,如果未能解决你的问题,请参考以下文章
[Functional Programming ADT] Debug a Functional JavaScript composeK Flow