[Functional Programming] Function modelling -- 10. Free Monads
Path: Compose Functors -> Monad Transformers -> Free Monad
Free monads, it provides a way to modelling functions as Data type. So composing / chaining data types to form the application.
We also need something called `interpret` which can automaticlly do partten matching and do actual tasks.
Read more: https://medium.com/@drboolean/free-er-monads-in-js-f5a59e7abc82
https://medium.com/@drboolean/free-er-monads-in-js-pt2-8ab3b9efa510
So, part one, how to modelling function as data type:
const { liftF } = require("../free"); const { Id } = require("../types"); const { taggedSum } = require("daggy"); const Http = taggedSum("Http", { Get: ["url"], Post: ["url", "body"], }); // Free Http Get const httpGet = (url) => liftF(Http.Get(url)); // Free Http Post const httpPost = (url, body) => liftF(Http.Post(url, body));
Using 'daggy' to build Http object.
So if you call:
Http.Get('/home') // {url: '/home'}
Then compose to an application:
const app = () => httpGet("/home").chain((contents) => httpPost("/analytics", contents)); const res = app().foldMap(interpret, Id.of);
Last thing is the 'interpret':
const interpret = (x) => x.cata({ Get: (url) => Id.of(`contents for ${url}`), Post: (url, body) => Id.of(`Post ${body} to ${url}`), });
--
Full code:
const { liftF } = require("../free"); const { Id } = require("../types"); const { taggedSum } = require("daggy"); /** * Data type to repersent function: * * * httpGet = url => HttpGet(url) * * HttpGet(url) * .chain(contents => HttpPost('/ayalytics', contents)) * */ const Http = taggedSum("Http", { Get: ["url"], Post: ["url", "body"], }); // Free Http Get const httpGet = (url) => liftF(Http.Get(url)); // Free Http Post const httpPost = (url, body) => liftF(Http.Post(url, body)); const interpret = (x) => x.cata({ Get: (url) => Id.of(`contents for ${url}`), Post: (url, body) => Id.of(`Post ${body} to ${url}`), }); const app = () => httpGet("/home").chain((contents) => httpPost("/analytics", contents)); const res = app().foldMap(interpret, Id.of); console.log(res.extract());
【推荐】国内首个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工具
2016-07-01 [RxJS] Drag and Drop example
2014-07-01 [Android] Content provider, ContentResolver