[Functional Programming] Unbox types with foldMap
with Programming types functional
2023-09-14 09:00:49 时间
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);
相关文章
- 【论文笔记】Unmasking DeepFakes with simple Features「建议收藏」
- SP4060 KPGAME - A game with probability
- ROS2机器人编程简述新书推荐-A Concise Introduction to Robot Programming with ROS2
- 【错误记录】Flutter 插件报错 ( Methods marked with @UiThread must be executed on the main thread. | 更新最新 SDK )
- ORA-26929: altering an outbound server with a remote capture is not allowed ORACLE 报错 故障修复 远程处理
- SQL开发知识:Oracle递归查询start with connect by prior的用法解析
- ORA-00842: DB_BLOCK_BUFFERS cannot be set with SGA_TARGET or MEMORY_TARGET ORACLE 报错 故障修复 远程处理
- ORA-08236: smsget: cannot share subcube with listener ORACLE 报错 故障修复 远程处理
- Using MySQL with C: Fast and Easy Programming(mysqlforc)
- Explore the Exciting World of Linux with EOG!(eoglinux)
- Unlocking the Power of Data with Linux: A Comprehensive Guide(linuxdata)
- Boost Your Programming Skills with Linux Development(linux开发程序)
- Mastering Multithreaded Applications with Linux: Boost Your Programming Skills(linux多线程应用)
- Secure Your MySQL Database With AntiInjection Code(mysql防注入代码)
- Exploring Code with Ease: Enhance Your Programming Skills with a Linux Code Reader(linux代码阅读器)
- 从Oracle中挖掘洞见坚实的With表(oracle with表)