[Compose] 8. A curated collection of Monoids and their uses
const { List } = require('immutable-ext'); const Right = x => ({ chain : f => f(x), ap : other => other.map(x), traverse : (of, f) => f(x).map(Right), map : f => Right(f(x)), fold : (f, g) => g(x), concat : o => o.fold(_ => Right(x), y => Right(x.concat(y))), toString : () => `Right(${x})` }) const Left = x => ({ chain : f => Left(x), ap : other => Left(x), traverse : (of, f) => of(Left(x)), map : f => Left(x), fold : (f, g) => f(x), concat : o => o.fold(_ => Left(x), y => o), toString : () => `Left(${x})` }); const fromNullable = x => x != null ? Right(x) : Left(null); const tryCatch = f => { try { return Right(f()) } catch( e ) { return Left(e) } }; let stats = List.of({ page : 'Home', view : 40 }, { page : 'About', view : 10 }, { page : 'Help', view : 4 }); const Sum = x => ({ x, concat : ({ x: y }) => Sum(x + y), toString : () => `Sum(${x})` }); Sum.empty = () => Sum(0); const res = stats.foldMap(x => fromNullable(x.view) .map(Sum), Right(Sum(0))); console.log(res.toString()); // Right(Sum(54))
If change the data a litte bit:
let stats = List.of({ page : 'Home', view : 40 }, { page : 'About', view : 10 }, { page : 'Help', view : null }); const Sum = x => ({ x, concat : ({ x: y }) => Sum(x + y), toString : () => `Sum(${x})` }); Sum.empty = () => Sum(0); const res = stats.foldMap(x => fromNullable(x.view) .map(Sum), Right(Sum(0))); console.log(res.toString()); // Right(Sum(50))
Because the view: null, then it will skip .map(sum).
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2014-12-16 [AngularJS] Introduction to ui-router